-1

Here is The My Array Code...

$data = array(
            'data_1',
            'data_2',
            'data_3',
            'data_4',
            'data_5' => array(
                            'data_5_1',
                            'data_5_2'
                        )
);

i Want to Ountput Like The : -

data_1
data_2
data_3
data_4
data_5
    data_5_1
    data_5_2

Here is My Code I try to Self But I Show Error

foreach($data as $da){ 
     echo $da."<br>";
}

Error Found Like This

data_1
data_2
data_3
data_4
Notice: Array to string conversion in filename.php on line 3
Array

Please Fix this problem & Use echo not print_r

2

3 Answers 3

2

This is best achieved with a recursive function so that you can deal with any level of nested arrays:

function display_list($array) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            echo "$k\n";
            display_list($v);
        }
        else {
            echo "$v\n";
        }
    }
}
display_list($data);

Output:

data_1
data_2
data_3 
data_4 
data_5 
data_5_1 
data_5_2

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

2 Comments

if I want Drop Down of The list Like i Select data_5 then show data_5_1 data_5_2
1

You could use iterators:

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $item)
  echo "$item<br>", PHP_EOL;

As asked in comments, if you want either the key or value depending on type, you can use the flag SELF_FIRST and the ternary operator:

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST) as $key => $item)
  echo (is_scalar($item) ? $item : $key) . '<br>', PHP_EOL;

3 Comments

This is pretty cool, but it doesn't print out the data_5 key value...
@Nick I've added a version also showing keys when the item is an array.
Looks good now, although it lost some of the nice cleanness that the first version had. pity...
0
foreach ($data as $val) {
    if(is_array($val)){
        foreach ($val as $row) {
            echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;".$row;
        }
    }
    else{ 
         echo "<br>".$val;
    }
}

1 Comment

data_5 Not Found in Output

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.