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

homelectshws
D2Lbreeze (snow day)

php-arrays
processing arrays

video from distance lecture (breeze), 2017-jan-31 (1h11m): hw01-soln review; arrays in PHP
Video (14m50s)

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.


An example function

Video (24m45s)

Suppose we want to write a function that takes an array of strings, and returns a string: the HTML for an ordered 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:  ", 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";
       
Once we have this, the code is straightforward:
/* 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>";
    }
       

Some thoughts about names:

1Or, numeric indices that aren't contiguous.      

homelectshws
D2Lbreeze (snow day)


©2017, Ian Barland, Radford University
Last modified 2017.Mar.18 (Sat)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.