Iterating Over Associative Arrays


#1

Cant see where the error is. Error code :Parse error: syntax error, unexpected $end on line 25. There is no line 25.
This is my coding:

    <title>Iteration Nation</title>
  </head>
  <body>
    <p>
      <?php    
$cars =array('style', 'make', 'colour');
$style = array('auto' => 'with',
                   'noise ' => 'without',
                   'sporty' => 'with');
      foreach ($carArray as $style=>$style) {
             
      $length = count($cars);
    for ($f = 0; $f <$length; $f++) {
        echo $car[$f] . '<br />';
}
      echo '<br /><br /> want my car to be:<br />';
      echo '<br /><br />';
           
          ?>
    </p>
  </body>
</html>

#2

The pattern for this statement is:

    foreach($Array as $key => $value)

Change one of your variables,

This site uses American English spelling, in case the SCT is checking.


#3

Thanks. I have now lost hope. Still cant make it work. This is my code now. My code prints out:
I want my car to be: get error message :Oops, try again. Did you create your own array on line 33?
My code is






<?php
$cars =array('style', 'make', 'color');
$style =array('auto' => 'with',
'noise ' => 'without',
'sporty' => 'with');
$length = count($cars);
for ($i = 0; $i <$length; $i++) {
}
echo '

I want my car to be:
';
echo '

';
?>



I have well and truly lost the will to live. Help!

#4

Copy your code and save it in a text editor. Then reset. Is this what you have to start with?

<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!
    

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