1
<?php
    $products = array();    
    $products[101] = array(
        "name" => "Logo Shirt, Red",
        "price" => 18,
        "img" => "img/shirts/shirts-101.jpg"
);
    echo $products;
?>

I am trying to run this php file and it keeps giving me this error - Notice: Array to string conversion in C:\xampp\htdocs\example\echo.php on line 8 Array.

All i want to do is echo out each and every element inside the array. I've also tried

<?php
    $products = array();    
    $products[101] = array(
        "name" => "Logo Shirt, Red",
        "price" => 18,
        "img" => "img/shirts/shirts-101.jpg"
    );
    foreach($products as $product){
        echo $product;
    }
?>

EDIT1: okay guys what if there are multiple similar arrays like $product[101] $product[102] $product[103] $product[104] . . . $product[n]

What then?

2
  • foreach($products[101] as $product) - foreach Commented Dec 10, 2015 at 17:26
  • @Fred -ii- yep, i tried googling it and didn't found anything useful Commented Dec 10, 2015 at 17:36

4 Answers 4

3

If you echo an array, it will either give you an error or just output "Array".

In your second example, $products[101] is also an array.

So you can do this:

foreach($products as $product){
    foreach($product as $key => $val){
        echo "$key: $val";
    }
}

Or use print_r to output the data in an array:

foreach($products as $product){
    print_r($product);
}
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to print the $products[101] just do the foreach but do

$products[101] as $product

instead

Comments

0

simply just use:

print_r($products) or

var_dump($products)

That should do it for you...cheers

Comments

0

print_r ($products); Use print_r method to print arrays.

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.