5

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.

2
  • If you have multiple keys/values in your array, would you want to display all, or just one? Commented Aug 25, 2014 at 7:23
  • For details you can visit phpfresher.com/tag/recursion-function Commented Aug 28, 2014 at 17:07

3 Answers 3

4

You have to use 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>';
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

3

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
(
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.