0

could someone explain me why I can not get the data from that array? My echo only returns "array". where I'm going wrong?

<?php
$people = array( 
array("name"=>"Bob","age"=>8,"colour"=>"red"), 
array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
array("name"=>"Andy","age"=>5,"colour"=>"purple")); 


foreach($people as $vperson => $person){ 

    echo $person;

} 
?>
3
  • 1
    Because your array is a nested array; each element of the $people array, is a sub-array Commented May 13, 2014 at 11:15
  • 2
    If you are looking to print the names ... Do this echo $person['name']; instead of echo $person; Commented May 13, 2014 at 11:16
  • use print_r instead of echo .. $vperson will print the key and $person will print the nested array Commented May 13, 2014 at 11:17

3 Answers 3

2

Well as you said you have an array, your variable $person is also an array so you can't just make echo on that. You can access values by the names "age, name and colour".

Try this:

<?php
$people = array( 
array("name"=>"Bob","age"=>8,"colour"=>"red"), 
array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
array("name"=>"Andy","age"=>5,"colour"=>"purple")); 


foreach($people as $vperson => $person){ 

    echo $name = $person['name'];
    echo $age = $person['age'];
    echo $colour = $person['colour'];
    echo "<br>";

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

2 Comments

Also you can do a var_dump inside your foreach, like this: var_dump($person) then you will get better how it works.
many thanks friend to fix my problem and give me the explanation.
0

Because, your are printing array with echo.

You can print the array like:

    <?php
    $people = array( 
    array("name"=>"Bob","age"=>8,"colour"=>"red"), 
    array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
    array("name"=>"Andy","age"=>5,"colour"=>"purple")); 
    foreach($people as $vperson => $person){ 
    echo '<pre>';
        print_r($person);
    echo '</pre>';


echo $name = $person['name'];
    echo $age = $person['age'];
    echo $colour = $person['colour'];
    } 

Comments

0

Use this to display key and equivalent value

foreach($people as $pe)
{
  foreach($pe as $key => $person) 
  {
     echo $key.' : '.$person.' </br> ';
  }
}

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.