1

I'm learning array and loop in php. But can't print the array with keys & values. How can I do this?

<?php
$marks = array (
    "Alice" => array (
        "physics" => "60",
        "math" => "65"
    ),
    "Bob" => array (
        "physics" => "40",
        "math" => "45"
    )
);

foreach ( $marks as $key => $value) {
    foreach ( $key as $key2 => $value2 ) {
        echo $key . " : " . $key2 . " - " . $value2 . "<br>";
    };
};
?>
1
  • 2
    second forEach should be like foreach ( $value as $key2 => $value2 ) { Commented Apr 7, 2019 at 15:40

3 Answers 3

2

In the nested foreach you have to iterate over the $value which holds the array.

foreach ( $marks as $key => $value) {
   foreach ( $value as $key2 => $value2 ) {
   // -------^^^^^^-------
      echo $key . " : " . $key2 . " - " . $value2 . "<br>";
   }
};
Sign up to request clarification or add additional context in comments.

Comments

2

Use this

foreach ( $marks as $key => $value) {
     foreach ( $value as $key2 => $value2 ) {
        echo $key . " : " . $key2 . " - " . $value2 . "<br>";
          }
       }

Comments

1

This way it could be more readable to fix it and clear up confusion:

     $marks = array(
        'Alice' => array(
            'physics' => 60,
            'math' => 65,
        ),
        'Bob' => array(
            'physics' => 40,
            'math' => 45,
        ),
    );

    // Loop students
    foreach($marks as $name => $grades){

        // Loop their grades
        foreach ($grades as $subject => $score){
            echo $name . ' : ' . $subject . ' - ' . $score . '<br>';
        }
    }

Please note that the numbers are without quotes. This will allow you to use them as numbers to do further calculations.

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.