-->

Notice: Array to string conversion in C:\\xampp\\h

2020-08-01 12:26发布

问题:

<?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?

回答1:

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);
}


回答2:

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

$products[101] as $product

instead



回答3:

simply just use:

print_r($products) or

var_dump($products)

That should do it for you...cheers



回答4:

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