Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the property/ value of an array which has been converted into an object?

How can I access the property/ value of an array which has been converted into an object? For instance, I want to access the value in the index 0,

$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj->0);

error,

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in C:...converting_to_object.php on line 11

like image 329
Run Avatar asked Apr 04 '12 14:04

Run


1 Answers

Trying this:

$obj = (object) array('test' => 'qualitypoint', 'technologies', 'India');

var_dump($obj->test);

The result is:

string(12) "qualitypoint"

But trying to access $obj->0, the same error shows up: Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'

If you loop through the object, tough, you can access the properties normally as an usual array:

foreach($obj as $x) {
    var_dump($x);
}

Apperantly, the property naming rules are the same as the basic variable naming rules.

If you convert it to an ArrayObject instead, you can access the index normally:

$obj = new ArrayObject(array('qualitypoint', 'technologies', 'India'));

And dumping it:

var_dump($obj[0]);

You would get:

string(12) "qualitypoint"
like image 78
Daniel Ribeiro Avatar answered Sep 30 '22 14:09

Daniel Ribeiro