Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP referring to object data with numerical key

Tags:

php

I have converted an array to object data like this:

<?php
$myobject->data = (object)Array('zero','one','two');
print_r($myobject);
?>

And the output is:

stdClass Object ( [data] => stdClass Object ( [0] => zero [1] => one [2] => two ) )

So far so good. But if I try to refer to the numerical keys...

<?php
$myobject->data = (object)Array('zero','one','two');
$counter = 1;
echo $myobject->data->$counter;
?>

...nothing is returned! I would expect it to echo "one".

Am I doing it wrong?

like image 540
Al. Avatar asked Nov 04 '09 12:11

Al.


2 Answers

That's an oddity in PHP, you need to access it using $object->data->{1}. Or you could convert it back to array for accessing the members. But I think it is best to have proper names for object members, try something like this, for example:

$myobject->data = (object)Array('m0' => 'zero','m1' => 'one','m2' => 'two');
$myObject->data->m1;
like image 78
soulmerge Avatar answered Sep 19 '22 13:09

soulmerge


You could try accessing it as an array element. But I'm not sure whether that would work or not. However, what you can do is looping over the object elements (or rather, properties) using a foreach loop.

Like so:

foreach ($myobject->data as $key => $value)
    echo "$key is my key.<br />";

I'm just not sure whether you can access the key, too.

like image 23
Franz Avatar answered Sep 20 '22 13:09

Franz