Casting an Array with Numeric Keys as an Object

Yes, they are just locked away unless cast back to an array. There are a few little “Gotchas” in PHP, for example in older versions you could define a constant as an array, but then never access its elements. Even now you can define a constant as a resource (e.g., define('MYSQL',mysql_connect());) although this leads to rather unpredictable behavoir and, again, should be avoided.

Generally, it’s best to avoid array-to-object casts if at all possible. If you really need to do this, consider creating a new instance of stdClass and then manually renaming all the variables, for example to _0, _1, etc.

$a = array('cat','dog','pheasant');
$o = new stdClass;
foreach ($a as $k => $v) {
    if (is_numeric($k)) {
        $k = "_{$k}";
    }
    $o->$k = $v;
}

EDIT: Just did one more quick test on this hypothesis, and yes, they officially “do not exist” in object context; the data is stored, but it’s impossible to access, and is therefore the ultimate private member. Here is the test:

$a = array('one','two','three');
$o = (object)$a;
var_dump(property_exists($o, 1), property_exists($o, '1'));

And the output is:

bool(false)
bool(false)

EDIT AGAIN: Interesting side-note, the following operation comes back false:

$a = array('one','two','three','banana' => 'lime');
$b = array('one','two','banana' => 'lime');

$y = (object)$a;
$z = (object)$b;

var_dump($y == $z);

Leave a Comment