|
home—lects—hws
D2L—breeze (snow day)
Arrays, and looping over them:
$frontRow = array( "Aaron", "Alvin", Isaac" ); echo $frontRow[1]; |
$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 ordered list.
echo "Actual: ", ol( array() ), "\n"; echo "Desired: ", "<ol type='1'> </ol>", "\n"; echo "Actual: ", ol( array( "Milk" ) ), "\n"; echo "Desired: ", "<ol type='1'> <li> Milk </li> </ol>", "\n"; echo "Actual: ", ol( array( "Milk", "Eggs", "Ice Cream!" ) ), "\n"; echo "Desired: ", "<ol type='1'> <li> Milk </li> <li> Eggs </li> <li> Eggs </li> </ol>", "\n"; |
/* ol: string[] → string * Return the html for an ordered list whose items are `$lis`. */ function ol( $lis ) { $lisSoFar = ""; foreach( $lis AS $li ) { $lisSoFar .= " <li>\n $li\n </li>\n"; } return "<ol type='1'>\n$lisSoFar</ol>"; } |
home—lects—hws
D2L—breeze (snow day)
©2017, Ian Barland, Radford University Last modified 2017.Sep.04 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |