RU beehive logo ITEC dept promo banner
ITEC 325
2016spring
ibarland

homelectshws
D2Lbreeze (snow day)

php-arrays
processing arrays

From previous notes but not mentioned explicitly: We can shorten ../Homeworks/hw01-soln/silly-page_php.txt to ../Homeworks/hw01-soln/silly-page-v2_php.txt.
(Self-quiz: Why can't pull up ../Homeworks/hw01-soln/silly-page.php and select Developer → View Source, to see the php code?)

Arrays, and looping over them:

         $frontRow = array( "Aaron", "Alvin", Isaac" );
         echo $frontRow[1];
       
To loop over an array, use foreach:
         $countA = 0;
         foreach ($frontRow as $student) {
           if ($substr($student,0,1)==="A") {
             $countA = $countA + 1;
             }
           }
         echo $countA . " names start with 'A'.";
       

Don't loop over an array using numeric indices in php: Many times arrays have non-numeric indices1. More examples (including using strings-as-indices): See php-ch02-simple.php.

Suppose we want to write a function that takes an array of strings, and returns a string: the HTML for an unordered list.

Note that part of your test case is deciding what is the desired amount of whitespace to be included in the answer.
echo "Actual:  ", stringsToUL( array() );
echo "Desired: ", "<ul>
</ul>
";

echo "Actual:  ", stringsToUL( array("Aaron") );
echo "Desired: ", "<ul>
     <li>Aaron</li>
</ul>
";

echo "Actual:  ", stringsToUL( array("Aaron", "Isaac", "Alvin") );
echo "Desired: ", "<ul>
     <li>Aaron</li>
     <li>Isaac</li>
     <li>Alvin</li>
</ul>
";
       
Once we have this, the code is straightforward:
/* stringsToUL : string[] -> string
 * Return the HTML for an unordered list, containing each element of $itms.
 * (Those strings may themselves contain HTML, so they are NOT SANITIZED HERE.)
 */
function stringsToUL( $itms ) {
  $lineItemsSoFar = "";
  foreach ($itms AS $itm) {
    $lineItemsSoFar .= "    <li>$itm</li>\n";
    }
  return "<ul>\n" . $lineItemsSoFar . "</ul>\n";
  }
       

In retrospect, the function-name stringsToUL is fine, but the name might be toUL might be equally good.


1Or, numeric indices that aren't contiguous.      

homelectshws
D2Lbreeze (snow day)


©2015, Ian Barland, Radford University
Last modified 2016.Jan.19 (Tue)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.