|
home—lects—exams—hws
D2L—breeze (snow day)
From previous notes but not mentioned explicitly:
We can shorten silly-page_php.txt
to
silly-page-v2_php.txt.
(Self-quiz:
Why can't pull up 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]; |
$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.
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> "; |
/* 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. ↩
home—lects—exams—hws
D2L—breeze (snow day)
©2015, Ian Barland, Radford University Last modified 2015.Sep.18 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |