0

I want to create a loop that prints a array as a '' but also keeps checking if the value is an array as well so that I can loop through that array too.

But I don't fully understand how I can keep checking if value is a array without using a very large amount of if statements.

My array:

$stuff = array('germany', 'java', 'help', array('hello', 'help', array('save', 'me', 'python')));

Output:

<ul>
    <li>germany</li>
    <li>java</li>
    <li>help</li>
    <ul>
        <li>hello</li>
        <li>help</li>            
        <ul>
            <li>save</li>        
            <li>me</li>        
            <li>python</li>        
        </ul>
    </ul>
</ul>
Wieb
  • 3
  • 2
  • Did you tried `is_array`? – dWinder Jun 23 '19 at 11:01
  • You can use recursion with `is_array()`, if you don't know the depth of the nested array. You can see here. https://stackoverflow.com/questions/3684463/php-foreach-with-nested-array – sujeet Jun 23 '19 at 11:02

2 Answers2

0

You can make use of recurcive function as

<?php
        //Enter your code here, enjoy!


$stuff = array('germany', 'java', 'help', array('hello', 'help', array('save', 'me', 'python')));

loop($stuff);

function loop($ary){
    echo "<ul>\n";
    foreach($ary as $val){
        if(is_array($val))
            loop($val);
        else
            echo "<li>".$val."</li>\n";
    }
    echo "</ul>\n";
}

This will give output as:

<ul>
<li>germany</li>
<li>java</li>
<li>help</li>
<ul>
<li>hello</li>
<li>help</li>
<ul>
<li>save</li>
<li>me</li>
<li>python</li>
</ul>
</ul>
</ul>

Working Demo here Feel free to ask any doubts.

Happy Coding :)

Rishabh Ryber
  • 446
  • 1
  • 7
  • 21
0

You can approach this by using the recursive function

function recurrsiveTraverseArray($arr, $html=null){
    $html = '<ul>';
    foreach($arr as $v){
      if(is_array($v)){
        $html .= recurrsiveTraverseArray($v, $html);
      }else{
        $html .= '<li>'.$v.'</li>';
      }
    }
    $html .= '</ul>';
    return $html;
  }

usage:

$stuff = array('germany', 'java', 'help', array('hello', 'help', array('save', 'me', 'python')));
echo recurrsiveTraverseArray($stuff);

Working DEMO

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20