1

So I have the following, working code:

$arrayitertest=Array("Fruit"=>Array("Pear","Peach","Apple","Banana"),"Cars"=>Array("My budget","other cars."));

foreach ($arrayitertest as $key=>$value)
foreach($arrayitertest[$key] as $result) echo $key.":". $result."|";

But when I change foreach ($arrayitertest as $key => $value) to foreach ($arrayitertest as $key) it throws a fatal error (despite the fact I never use the $key variable.)

The Error is:Invalid argument supplied for foreach() in

Could someone be so kind as to tell me why that happens ?

Edit: Wow, thanks for all the answers.... I will give the accept to the most specific one as of this moment though.

10
  • 2
    Can you post the error? Also in the first foreach you have $key/$value vars backwards. Commented Mar 7, 2013 at 23:47
  • 2
    You have a bracket that isn't closed after the first foreach. Commented Mar 7, 2013 at 23:49
  • Brackets are also missing entirely from the second foreach. Commented Mar 7, 2013 at 23:50
  • 1
    Your foreach is backwards. It's $kay => $value Commented Mar 7, 2013 at 23:50
  • What @shapeshifter said. Your commenting out the closing bracket. Change //echo $value."|".$key1."\n"; to /*echo $value."|".$key1."\n";*/ to correctly comment out the code within the foreach. Commented Mar 7, 2013 at 23:51

3 Answers 3

4

As far as your error is concerned: If you remove the $value from the first foreach, $key becomes the value and $arrayitertest[$key] becomes "pear" which is an invalid argument for the second foreach.

Your program would halt on:

// this is not going to work
foreach ("pear" as $result)

If you don't need the key of the first foreach you can just change it to:

foreach ($arrayitertest as $value)
{
   foreach($value as $result)
   {
   }
}
Sign up to request clarification or add additional context in comments.

Comments

3

I think you are misunderstanding the order of key and values. Where you say $value => $key it's technically $key => $value.

The way to parse your array is this:

foreach ($array as $key => $value) {
    foreach ($array[$key] as $v) {
        // $v = Pear (1st iteration), Peach (2nd), Apple (3rd) ... (for key = Fruit) 
        // $v = My Budget (1st iteration), other cars. (2nd) (for key = Cars)
        // notice that $key is also accessible here
    }
}

Obviously if you don't need the $key either you can simply:

foreach ($array as $a)
    foreach ($a as $v)
        // use $v here 

Comments

0

Coding $value => $key, puts Fruit, Car, ... into $value.

Coding just $value puts the arrays such as Array("Pear","Peach","Apple","Banana") into $value and that is not a valid index for an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.