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

homelectshws
D2Lbreeze (snow day)

lect07-arrays
processing arrays

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];
       
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 "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>
";
       
Once we have this, the code is straightforward:
/* 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 "
    \n" . $lineItemsSoFar . "
\n"; }


1Or, numeric indices that aren't contiguous.      

homelectshws
D2Lbreeze (snow day)


©2014, Ian Barland, Radford University
Last modified 2015.Feb.02 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.