Not All Strings In Arrays¶
<?php
class A {
function __toString() {
return "A";
}
}
$a = new a;
$b = [$a => $a]; //Illegal offset type
print_r($b);
Array keys are coerced into strings or integers, while array values are left intact.
Yet, this doesn’t apply to array keys, so this code will display an Uncaught TypeError: Illegal offset type, even without strict_types.
This code needs an explicit cast to string to work.
See Also¶
string or not? [Try me]
PHP Features¶
Last updated: 14 July 2026