0

I am trying to create a multi-dimensional associative array and display all of its values.

How do I do that using for loop?

Similar code:

$StudScore = array( 
    "Mary" => array(
        "physics" => 35,        
        "maths" => 30,      
        "chemistry" => 39       
    ),
    "Tom" => array(
        "physics" => 30,
        "maths" => 32,
        "chemistry" => 29
    ),
    "Jon" => array(
        "physics" => 31,
        "maths" => 22,
        "chemistry" => 39
    )
);
2
  • 2
    using foreach to loop the array Commented Oct 15, 2015 at 1:56
  • if you just want to display the contents of an array (or any variable), use var_dump Commented Oct 15, 2015 at 3:10

1 Answer 1

1

Look at this recursive function and see if it fits:

function echoArray($array) {
    foreach ($array as $key => $value) {
        echo "<li>$key</li>";
        if (is_array($value)) {
            echo "<ul>";
            echoArray($value);
            echo "</ul>";
        } else {
            echo "<ul><li>$value</li></ul>";
        }
    }
}

Change the way you display each item as you wish.

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

2 Comments

You never echo the values, just the keys.
Typo... fixed! Thanks.

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.