0
$shop = array( 
                array("Rose", 1.25 , 15),
                array("Daisy", 0.75 , 25),
                array("Orchid", 1.15 , 7)
            );


    for($i = 0; $i <= count($shop); $i++){
        foreach($shop[$i] as $key => $val)
            echo $key . ' = ' . $val . '<br>';
    }

So this is the output I'm getting:

0 = Rose

1 = 1.25

2 = 15

0 = Daisy

1 = 0.75

2 = 25

0 = Orchid

1 = 1.15

2 = 7

============================================

But then I get an error:

Warning: Invalid argument supplied for foreach()

What I want to know is how to correct this, and if there's a more efficient way to write what I'm trying to output?

Thanks guys.

3 Answers 3

2

The problem is, your using <= instead of <. So your for loop goes one step to far and the array is out of bounds.

for($i = 0; $i < count($shop); $i++){
    foreach($shop[$i] as $key => $val)
        echo $key . ' = ' . $val . '<br>';
}
Sign up to request clarification or add additional context in comments.

3 Comments

or 2 foreach rather than the for
I feel dumb. Thanks budd!
No need to - sometimes one doesn't see the obvious
1

When iterating through an array, always use a foreach instead of a for loop.

foreach ($shop as $foo) {
    foreach ($foo as $key => $val) {
        echo $key . ' = ' . $val . '<br />';
    }   
}

Comments

0
foreach ($Array AS $Values){
    if (is_array($Values)){
        foreach ($Values AS $Inner){
            echo $Inner;
        }
    }else{
        echo $Values;
    }
}

I Personally would go for 2 foreach loops. Check if the value passed is an array, if it is. Step in. If not, print the value

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.