Quotes help make search much faster. Example: "Practice Makes Perfect"

Friday, April 26, 2013

Codecademy Sample Solution: Iterating Over Associative Arrays



<html>
  <head>
    <title>Iteration Nation</title>
  </head>
  <body>
    <p>
      <?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!
      $gadget = array('programming' => 'iMac', 'calls' => 'iPhone', 'ebooks' => 'iPad');
      foreach ($gadget as $key => $value){
        echo "I use the ".$value." for ".$key.".<br/>";
      }

      ?>
    </p>
  </body>
</html>

No comments:

Post a Comment


This is an example of scrolling text using Javascript.

Popular Posts