Iterating Over Associate Arrays 5/7 What is $i?


#1

Can someone please explain what $i stands for in the below code? Does it stand for "ingredient" ($ingredient)?

<?php
$food = array('pizza', 'salad', 'burger');
$salad = array('lettuce' => 'with',
'tomato' => 'without',
'onions' => 'with');

  // Looping through an array using "for".
  // First, let's get the length of the array!
  $length = count($food);

  // Remember, arrays in PHP are zero-based:
  for ($i = 0; $i < $length; $i++) {
    echo $food[$i] . '<br />';
  }

  echo '<br /><br />I want my salad:<br />';

  // Loop through an associative array using "foreach":
  foreach ($salad as $ingredient=>$include) {
    echo $include . ' ' . $ingredient . '<br />';
  }

  echo '<br /><br />';

  // Create your own array here and loop
  // through it using foreach!


  ?>

#2

$i is the control variable, or iterator. It points to the respective indices, one each iteration of an array.

    for ($i = 0; $i < count($food); $i++) {
        echo $food[$i] . '<br>';
    }

Output

pizza    // @ index[0] of $food array
salad    //        [1]
burger   //        [2]

With the foreach statement we can see the difference. It does not use a numerical index, but keys associated with values in the associative array (hash).

    foreach ($hash as $key => $value) {
        // 
    }

#3

I passed 5/7 but I'm trying to figure out if my code is correct. There is no space between the two statements on the preview screen. Your feedback would be appreciated.

$laura = array('eyes' => 'brown',
'skin' => 'white');

foreach ($laura as $feature=>$color) {
    echo 'Laura has ' . $color . ' ' . $feature .'';
    }

#4

Just add a line break, as follows...

echo 'Laura has ' . $color . ' ' . $feature .'<br>';

#5

Thank you! :blush:

Two more lessons to go and I'm done with PHP basics.