-2

I create an associative array in which there is an array, I want to print an associative array (key) and an array that is in it (value)

I have tried using a foreach but only managed to print the key but it shows an error for its value (Error: Array To String Conversion).

The second experiment, I tried using the foreach loop for the key and then used the loop for to print the value (Error: Undefined Offset).

<?PHP
      $siswa = array(
        "Kelas-X" => array("Joko", "Budi", "Duduk"),
        "Kelas-XI" => array("Entong", "Timun", "Opang"),
        "Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
    );
    foreach($siswa as $key => $value){
        echo "Key : " . $key . "Value : " . $value;
        }
?>
0

2 Answers 2

1

You cannot use echo on an array, you have to convert it to string before.

You can use json_encode for that.

Like this :

echo "Key : " . $key . "Value : " . json_encode($value);
Sign up to request clarification or add additional context in comments.

1 Comment

I think you misinterpret the question.
0

Use two foreach loop

<?php 

$siswa = array(
    "Kelas-X" => array("Joko", "Budi", "Duduk"),
    "Kelas-XI" => array("Entong", "Timun", "Opang"),
    "Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
);

foreach($siswa as $key => $value){
   foreach($value as $k => $v){
     echo "Key : " . $key. "Value : " . $v;      

  }
}

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.