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?
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?
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)
Try using foreach
loop. This will eliminate the Array
and display your wanted output.
<?php
$foo = array('mouse', 'cat', 'dog');
foreach ($foo as $key => $value) {
echo "[$key] $value ";
}
?>
output:
[0] mouse [1] cat [2] dog