1

I want to loop through an array within and array. I'm new to loops and I am struggling reading through the documentation.

$data holds the below.

Array
(
    [products] => Array
        (
            [0] => Product1
            [1] => Product2
        )
)

I'm wanting to use foreach loop and i have tried.

foreach($data as $key){
    echo $key->products
}

I want to be able to echo out Product 1 and Product 2 separately.

1
  • Move the reference to products(and it should be an array reference), so try foreach($data['products'] as $key){ Commented Sep 2, 2019 at 12:30

4 Answers 4

1
foreach($data as $value) {
    foreach($value as $product) {
        var_dump($product);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it in 2 ways using foerach

  1. You can break the products into Key Value
foreach( $products as $key => $values) {
    //echo $key. This will print products 
    foreach( $values as $value ) {
       echo $value; //This will print individual products.
    }
}

  1. But its Better way to do as following in this case by directly supplying foreach the array that you want to loop
foreach( $data['products'] as $product ) {
    echo $product;
}

Comments

0

If you want array convert to object shortly use type object casting



$productsObject= (object) $array;

print_r($productsObject->products));

If you are array iterator

foreach($data['products'] as $key){

  echo $key;

}

If you use advanced techniques maybe u can use ArrayObject class

Comments

0

Do it with single foreach() along with products index.

<?php
$data = array
(
    'products' => array
        (
            'Product1',
            'Product2'
        )
);

foreach( $data['products'] as $product ) {
    echo $product.PHP_EOL;
}
?>

DEMO: https://3v4l.org/bn2KN

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.