0

I have this piece of code:

$object = new StdClass();
$object->{'1'} = 'test_1';
$object->a = 'test_a';
$array = (array) $object;

var_dump($array) works fine, returns

array (size=2)
  '1' => string 'test_1' (length=6)
  'a' => string 'test_a' (length=6)

however,

var_dump($array[1]);   //returns null
var_dump($array['1']); //returns null
var_dump($array["1"]); //returns null

Can someone explain this behaviour? Why can't I access a property that I can see is there?

ilyes kooli
  • 11,959
  • 14
  • 50
  • 79

1 Answers1

1

Your result is fine. It is as it's expected in PHP - since string keys that are numerics actually will be converted to integers - both within definition of array or within attempt to dereference them. It's not how you're supposed to use arrays - i.e. converting an object. Yes - such conversion is a way to get string numeric keys - but the consequences are your own.

You can extract such values via:

function getValue($array, $key)
{
   foreach($array as $k=>$value)
   {
      if($k===$key)
      {
         return $value;
      }
   }
   return null;
}

$object = new StdClass();
$object->{'1'} = 'test_1';
$object->a = 'test_a';
$array = (array) $object;

var_dump(getValue($array, '1'), getValue($array, 1));

-but I definitely don't recommend to use arrays in such manner.

To say more - there are such things as ArrayAccess in PHP that allows you to implement custom logic for your data-structure - and, using them, you'll able to overcome this restriction in normal way.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • 1) I was there before coming here, but is not the same case, if it's only about casting the numeric keys to integer, I'm still able to get $array[1]. 2) I know how to overcome the problem, but I want to understand what's happening – ilyes kooli Nov 29 '13 at 14:46
  • So I've explained that by _'string keys that are numerics actually will be converted to integers - both within definition of array or within attempt to dereference them'_ - i.e. PHP will treat `"1"` as `1` within array definition or accessing it's element via `[]` – Alma Do Nov 29 '13 at 14:47