|
home—lects—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 "Expect: ", "<ul> </ul> "; echo "Actual: ", stringsToUL( array("Aaron") ); echo "Expect: ", "<ul> <li>Aaron</> </ul> "; echo "Actual: ", stringsToUL( array("Aaron", "Isaac", "Alvin") ); echo "Expect: ", "<ul> <li>Aaron</> <li>Isaac</> <li>Alvin</> </ul> "; |
/* stringsToUL : string[] -> string * Return the HTML for an unordered list, containing each element of $itms. */ function stringsToUL( $itms ) { $lineItemsSoFar = ""; foreach ($itms AS $itm) { $lineItemsSoFar .= " <li>$itm</li>\n"; } return "
|
1Or, numeric indices that aren't contiguous. ↩
home—lects—hws
D2L—breeze (snow day)
©2014, Ian Barland, Radford University Last modified 2015.Feb.02 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |