Convert an object to an indexed array

Possible duplicate:
Listing an array with numeric keys as an object

I was interested to know about the type (object) .

You can do many useful things, for example, converting an associative array to an object, and some not very useful and slightly funny (IMHO) things, for example converting a scalar value to an object .

But how can I access the cast result of an indexed array?

 // Converting to object an indexed array $obj = (object) array( 'apple', 'fruit' ); 

How to access a specific value?

 print $obj[0]; // Fatal error & doesn't have and any sense print $obj->scalar[0]; // Any sense print $obj->0; // Syntax error print $obj->${'0'}; // Fatal error: empty property. print_r( get_object_vars( $obj ) ); // Returns Array() print_r( $obj ); /* Returns stdClass Object ( [0] => apple [1] => fruit ) */ 

The following works because stdClass implements dynamically Countable and ArrayAccess :

 foreach( $obj as $k => $v ) { print $k . ' => ' . $v . PHP_EOL; } 
+7
source share
1 answer

This actually reported an error .

This is considered "too costly to fix," and the documentation was "updated to describe this useless quirk, so now it's officially the correct behavior" [1] .

However, there are workarounds .

Since get_object_vars gives nothing, only you can do the following:

  • You can iterate over stdClass using foreach
  • You can drop it as an array.
  • You can change it to an object using json_decode + json_encode (this is a dirty trick)

Example 1 .:

 $obj = (object) array( 'apple', 'fruit' ); foreach($obj as $key => $value) { ... 

Example 2 .:

 $obj = (object) array( 'apple', 'fruit' ); $array = (array) $obj; echo $array[0]; 

Example 3 .:

 $obj = (object) array( 'apple', 'fruit' ); $obj = json_decode(json_encode($obj)); echo $obj->{'0'}; var_dump(get_object_vars($obj)); // array(2) {[0]=>string(5) "apple"[1]=>string(5)"fruit"} 

That is why you should not use a non-associative array as an object :)

But if you want, do it like this:

 // PHP 5.3.0 and higher $obj = json_decode(json_encode(array('apple', 'fruit'), JSON_FORCE_OBJECT)); // PHP 5 >= 5.2.0 $obj = json_decode(json_encode((Object) array('apple', 'fruit'))); 

instead

 $obj = (Object) array('apple','fruit'); 
+3
source

All Articles