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?

3
  • 2
    Look at this answer and comments: stackoverflow.com/a/4345609/722135 Commented Nov 29, 2013 at 14:28
  • Can you explain what inaccessible stands for? since var_dump display it, also a foreach display it too! Commented Nov 29, 2013 at 14:32
  • It's a PHP "feature" (a.k.a. bug). Commented Nov 29, 2013 at 14:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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 []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.