Quantcast
Channel: PHP Freaks: PHP Help
Viewing all articles
Browse latest Browse all 13200

Why is my array foreach not displaying correctly?

$
0
0

Check out my third array. It's only printing out "Reese's" and "gummy worms."

I want it to display "M&M's," "Snickers," "Reese's," "gummy bears," and "gummy worms."

I'm doing this for my codecademy course. The important part starts on line 33.

I'm new to coding.

<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!
    $candy = array('chocolate'=> 'M&Ms', 
                'chocolate'=>'Snickers', 
                'chocolate'=>'Reese\'s', 
                'gummy'=>'bears', 
                'gummy'=>'worms');
    foreach ($candy as $type => $specific):
        if ($type == 'chocolate'){
            echo $specific."<br></br>";
        } else {
            echo $type . ' ' . $specific;
        }
        continue;
    endforeach;
      ?>
    </p>
  </body>
</html>

Viewing all articles
Browse latest Browse all 13200

Trending Articles