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?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.