I've tried to print the number 200 from this array but I don't know how to do it with the (object) cast.
$x= [(object)["items"=>[1=>100,2=>200]]];
You shouldn't cast an array to an object blindly, because it's not safe. PHP explicitly warns against this in the manual.
An array converts to an object with properties named by keys and corresponding values, with the exception of numeric keys which will be inaccessible unless iterated.
Which means that any numeric keys in an array that's cast to an object will become inaccessible. In this particular case, the only key in the array being cast happens to be a string, which means that $x->items[2]
will give the expected result.
So for example, $x = (object) [1=>100,2=>200]
will result in $x[2]
and $x["2"]
to always be null despite var_dump($x)
showing otherwise. Which might be very peculiar to the casual observer.
As such, if what you want is to cast arrays to object safely you could use this approach instead.
function recursiveArrayToObject(Array $arr, stdClass $obj = null) {
if (!$obj) {
$obj = new stdClass;
}
foreach($arr as $key => $value) {
if (is_array($value)) {
$obj->$key = recursiveArrayToObject($value);
} else {
$obj->$key = $value;
}
}
return $obj;
}
$x = ["items"=>[1=>100,2=>200]];
$xObj = recursiveArrayToObject($x);
var_dump($xObj);
This gives you...
object(stdClass)#1 (1) { ["items"]=> object(stdClass)#2 (2) { ["1"]=> int(100) ["2"]=> int(200) } }
So now $xObj->items->{"2"}
will give you 200
, as expected.
If you want the safe, non-recursive version...
function arrayToObject(Array $arr, stdClass $obj = null) {
if (!$obj) {
$obj = new stdClass;
}
foreach($arr as $key => $value) {
$obj->$key = $value;
}
return $obj;
}
$x = ["items"=>[1=>100,2=>200]];
$xObj = arrayToObject($x);
var_dump($xObj, $xObj->items[2]);
Output...
object(stdClass)#1 (1) { ["items"]=> array(2) { [1]=> int(100) [2]=> int(200) } } int(200)