Ryan Ryan - 5 months ago 10
PHP Question

When printing an array, how do you remove the annoying "Array ( )"

Currently, I have an array, but when I print it using print_r it comes out something like:



Array (

[0] mouse

[1] cat

[2] dog

}





My question is, is it possible to ONLY print out the array contents, and not the "Array ( )" in there?

Answer

There are various ways like this:

Simple foreach

$arr = ['mouse', 'cat', 'dog'];

foreach ($arr as $key => $value) {
    echo "[$key] $value<br/>";
}

Using array_walk:

array_walk($arr,function($value,$key){
    echo "[$key] $value<br/>";
});

Result:

[0] mouse
[1] cat
[2] dog

Incase you needn't any index, just want to print the values:

foreach ($arr as $value) {
    echo "$value<br/>";
}

Using array_map

array_map(function($value){
    echo "$value<br/>";
}, $arr);

Results:

mouse
cat
dog

You can use implode to join the array values and print as a string:

echo implode(",", $arr);

You can also use join which is alias of implode:

echo join(",", $arr);

prints:

mouse,cat,dog

You can also use json_encode format to convert your array to JSON

echo json_encode($arr);

prints:

["mouse","cat","dog"]

(credits: @here2Help)

Comments