Click here to Skip to main content
15,877,533 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Problem/Question: Print the following multidimensional array, using foreach.

$grades = array(
"ali"=>array("php","50"),
"sami"=>array("php","77"),
"rami"=>array("php" )
);


What I have tried:

My code so far...

foreach ($grades as $ar_element)
{
     echo $ar_element;
     
    foreach($grades as $index => $value)
    {
         echo " Name: ".$index." , ";
    }
    
}


But, It gives me this error:

Quote:
Warning: Array to string conversion in /tmp/kF1L1NVkwY.php on line 12
Array Name: ali , Name: sami , Name: rami ,
Warning: Array to string conversion in /tmp/kF1L1NVkwY.php on line 12
Array Name: ali , Name: sami , Name: rami ,
Warning: Array to string conversion in /tmp/kF1L1NVkwY.php on line 12
Array Name: ali , Name: sami , Name: rami ,


I'm trying to have the output be something similar to:
Name: ali, Class: php ,Grade: 50

I tried researching a similar problem, but didn't find anything helpful.
I'm also a beginner in PHP.

Thank you in advance.
Posted

Try this:
PHP
foreach($grades as $index => $value)
{
    echo " Name: ".$index." , value: ";
    print_r($value);
}

or this
PHP
foreach($grades as $index => $value)
{
    echo " Name: ".$index." , values: ";
    foreach($value as $elt)
        echo $elt.", ";
    echo "\n";
}
 
Share this answer
 
Comments
Rama2F 3-Jan-24 12:48pm    
Thank you
This is just a small problem because the variable name in your second loop is wrong
PHP
foreach ($grades as $ar_element)
{
     echo $ar_element;
     
    foreach($ar_elementas $index => $value)
    {
         echo " Name: ".$index." , ";
    }
    
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900