0

May I know how to get the "product" value with foreach loop in PHP?

Array
(
    [0] => Array
        (
            [product] => "Sony"
        )

    [1] => Array
        (
            [product] => "Toshiba"
        )

    [2] => Array
        (
            [product] => "A4Tech"
        )

)

This is my code and I know it is not working after I tried it.

foreach($response as $key => $value){           

    foreach($key as $pic_small => $value2){

    echo $pic_small;
    }
}

2 Answers 2

4
foreach($response as $item)
   echo $item['product'];

ps: ok, foreach statement takes every first level element of $response array and set $item variable equal to it (you do not need indexes of the elements, so instead of the $key => $value only $value could be used). at the first loop it is the same as $item = array('product' => 'Sony');, at the second loop it is the same as $item = array('product' => 'Toshiba'); and so on..

you may, of course, use the second foreach loop to deal with those arrays, but if you need the value of only one associative element with key product then you can access it directly through the value of $item['product'].

otherwise, as it is shown in another answer, you can done it as

// $item1 means element of the first level in the original array
// $key2 and $value2 are keys and values of the second level elements 
foreach($response as $item1)
     foreach($item1 as $key2 => $value2) // you may remove '$key2 =>' here
        echo $value2;
Sign up to request clarification or add additional context in comments.

3 Comments

Care to write a sentence? It's rampant, but not actually good style to turn Stackoverflow into a code dump.
@mario but the code is so obvious that it does not require any explanation.
It is very much so. But obviously not to OP.
0
foreach($response as $key => $value){           

    foreach($value as $title => $value2){

        echo $value2;
    }
}

1 Comment

That's the right answer. Except that it also lacks the explanation part.

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.