0

After years of confusion I am trying to get to grips with PHP arrays and especially in combination with foreach loops.

There are various similar questions but I am really trying to understand why this is NOT working rather than make it work per se (will be using lots of foreach loops and arrays in more complicated stuff shortly).

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"37");

Have a simple foreach loop:

foreach ($age as $ages )
{
    n();n();
    echo($ages);
    n();
    $v="volvo";
    $key = key($age);
    if ($age["Ben"]==$ages)
    {
        echo "<BR><BR>Result is  $key is $ages <BR>";
    }
}

Output is:

35
37
Result is Ben is 37 
37
Result is Ben is 37 

All fine but I was expecting the last name to be Joe.

I thought that a foreach looped through each array value pair as a KEY VALUE pair. So why am I getting Ben twice?

BeNice
  • 2,165
  • 2
  • 23
  • 38

1 Answers1

1

Use foreach in the following way: foreach ($age as $name=>$personAge )

uri2x
  • 3,162
  • 1
  • 11
  • 25
  • Thanks have seen that but trying to understand what was going on in the original. What was I accessing by my original ` $key = key($age)`. Why Ben as answer. It looped twice with value 37...On the third time the VALUE was 37 but it came from Joe... Yes I can make it work using a `var =>var` form but still confused. Thanks for the pointer. – BeNice Aug 27 '15 at 22:41