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>
2
  • Did you tried is_array? Commented Jun 23, 2019 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. stackoverflow.com/questions/3684463/… Commented Jun 23, 2019 at 11:02

2 Answers 2

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

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

Comments

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

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.