0

I have an array of objects and I would like to access the values by the keys.

    <?php

    $name = [
                [
                    'firstname'  => 'John',
                    'lastname'   => 'Doe',
                    'middlename' => 'Bray'
                ],
                [
                    'firstname'  => 'John2',
                    'lastname'   => 'Doe2',
                    'middlename' => 'Bray2'
                ]           
    ];

    $count = count($name);
    for($i = 0; $i < $count; $i++){
        $cell = $name[$i];
        echo $cell->lastname;
        echo $cell->middlename;
    }   
?>

I thought that the 2 last lines would do but I get an error! What do I need to do o make it work?

Regards, Elio Fernandes

Elio Fernandes
  • 1,335
  • 2
  • 14
  • 29

3 Answers3

3

Change

echo $cell->lastname;
echo $cell->middlename;

with

echo $cell['lastname'];
echo $cell['middlename'];
Rahi
  • 1,435
  • 1
  • 12
  • 20
2

change

echo $cell->lastname;

to

echo $cell['lastname']; 

You are playing with an array not an object.

Moreover, you can use foreach loop instead of for as you won't have to get count and loop till count.

 foreach($name as $cell){...
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
0

$cell is an associative array, not an object. The syntax for accessing elements in an associative array is $arr['key']. The syntax for accessing properties of objects is $obj->prop.

So, use it like this:

echo $cell['lastname'];
echo $cell['middlename'];
Ethan
  • 4,295
  • 4
  • 25
  • 44