Printing the value of a multidimensional array without any key

I want to print an array where I do not know the dimension of the array value. Now the fact, when I use echo '<pre>' and then print_r($array) , will display Key and value with <br> . But I want to display only the value, not the array key. This $array may contain the multidimensional value of the array, or one value or both.

+5
source share
3 answers

You should use a recursive function:

 $array_list = array('a',array(array('b','c','d'),'e')); // Your unknown array print_array($array_list); function print_array($array_list){ foreach($array_list as $item){ if(is_array($item)){ print_array($item); }else{ echo $item.'<br>'; } } } 
+4
source

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

+4
source

In short, you can 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, try the following:

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

Conclusion:

 1 2 3 4 stdClass Object ( ) 
+3
source

Source: https://habr.com/ru/post/1201053/


All Articles