I feel really stupid right now. The following code should output ‘If you can get this text to print, you’re neat!’, but it doesn’t. Any ideas?
<?php
$a = (Array) json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}");
// dump($a);
echo $a[406]."\n";
echo $a["406"]."\n";
echo $a['"406"']."\n";
echo $a["'406'"]."\n";
$a = Array(406=>'Sanity check: this works, why don\'t any of the previous accessors work?');
// dump($a);
echo $a[406]."\n";
function dump($a) {
foreach ($a as $k => $v) {
echo "$k=>$v\n";
}
}
?>
Your original example was returning an object because of a second optional parameter for return type that has the default of
FALSE, or to return an object. This is how you would treat it…A little tweaking and you can create an array instead…
… and you can reference
$aas an array like you were originally attempting. Notice what was happening when you were trying to type cast the original object. Here’s a var_dump of the original array you created followed by the resulting array from using the optionalTRUEparameter.Do you see how it was adding the quotes to your array key when you were type casting it from an object? This is why you weren’t able to return the correct value; because the array key had changed.