RU beehive logo ITEC dept promo banner
ITEC 325
2018fall
ibarland

processing arrays

video: arrays in PHP (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.

Example array-usage (including using strings-as-indices): php-ch02-simple.php.


An example function

video: arrays in php example: ol (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:

1 Or, numeric indices that aren't contiguous.      

logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated 2018.Sep.10 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.