I want to print a array where I don't know the dimension of the array value.
Now the fact is when I use echo '<pre>' and then print_r($array) it will show the Key and value with <br> display.
But I want to display only the value and not the key of the array. That $array may contain multi-dimensional array value or single value or both.
-
If you have multiple keys/values in your array, would you want to display all, or just one?lucasem– lucasem2014-08-25 07:23:44 +00:00Commented Aug 25, 2014 at 7:23
-
For details you can visit phpfresher.com/tag/recursion-functionMd Riad Hossain– Md Riad Hossain2014-08-28 17:07:40 +00:00Commented Aug 28, 2014 at 17:07
Add a comment
|
3 Answers
try this Recursive function
function print_array($array, $space="")
{
foreach($array as $key=>$val)
{
if(is_array($val))
{
$space_new = $space." ";
print_array($val, $space_new);
}
else
{
echo $space." ".$val." ".PHP_EOL;
}
}
}
See Demo
Comments
In a short, you may use a recursive function for what you want to achieve:
function print_no_keys(array $array){
foreach($array as $value){
if(is_array($value)){
print_no_keys($value);
} else {
echo $value, PHP_EOL;
}
}
}
Another way is to use array_walk_recursive().
If you want to use indentation, then try this:
function print_no_keys(array $array, $indentSize = 4, $level = 0){
$indent = $level ? str_repeat(" ", $indentSize * $level) : '';
foreach($array as $value){
if(is_array($value)){
print_no_keys($value, $indentSize, $level + 1);
} else {
echo $indent, print_r($value, true), PHP_EOL;
}
}
}
Example:
<?php
header('Content-Type: text/plain; charset=utf-8');
$a = [1, [ 2, 3 ], 4, new stdClass];
function print_no_keys(array $array, $indentSize = 4, $level = 0){
$indent = $level ? str_repeat(" ", $indentSize) : '';
foreach($array as $value){
if(is_array($value)){
print_no_keys($value, $indentSize, $level + 1);
} else {
echo $indent, print_r($value, true), PHP_EOL;
}
}
}
print_no_keys($a);
?>
Output:
1
2
3
4
stdClass Object
(
)