6

Possible Duplicate:
Casing an Array with Numeric Keys as an Object

I made a casting from array to object and I'm confused:

$arr = range(1,3);
$obj = (object) $arr;
var_dump($obj)

object(stdClass)#2 (5) {
  [0]=>
    int(1)
  [1]=>
    int(2)
  [2]=>
    int(3)
}

The question is: How to access the object attributes in this case? $obj->0 causes syntax error.

1
  • Presumably $obj->{0} fails as well? Commented Apr 19, 2012 at 21:04

3 Answers 3

4

You can't access these object properties unless you cast back to an array. Period. If you have to do this for some reason, set the array keys to something else.

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

Comments

2

In this case the only thing I can think is to access properties using a foreach like this:

foreach($obj as $key => $value)
   var_dump("$key => $value");

but of course this won't solve the base problem.

1 Comment

Okay, that's not my problem - I just wanted to know. Yet again I conviced myself that PHP is strange. Sorry for duplication!
1

It appears that the ArrayObject class can access the properties

$a = new ArrayObject($obj);
echo $a[0];

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.