php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51015 Array keys can not be used to get values
Submitted: 2010-02-11 13:57 UTC Modified: 2010-02-12 18:48 UTC
From: nat at search dot ch Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.3.1 OS: Linux #1 SMP 2009-08-15 17:53:59
Private report: No CVE-ID: None
 [2010-02-11 13:57 UTC] nat at search dot ch
Description:
------------
In an associative array with number as text keys, the keys can not be used to get the values. "Foreach" works.

  var_dump($choices);      
// array(2) { ["1"]=>  array(2) { [0]=>  string(1) "0" [1]=>  string(1) "1" } ["0"]=>  array(2) { [0]=>  string(1) "0" [1]=>  string(1) "1" } }

  var_dump($choices['1']); // NULL
  var_dump($choices[1]);   // NULL
  var_dump($choices["1"]); // NULL
  var_dump($choices->{1}); // NULL
  var_dump($choices->{'1'});//NULL
  var_dump($choices['0']);  //NULL
  var_dump($choices[0]);    //NULL

 foreach ($choices as $k => $v) {
    var_dump($k, $v);
  }

// string(1) "1" array(2) { [0]=> string(1) "0" [1]=> string(1) "1" }
// string(1) "0" array(2) { [0]=> string(1) "0" [1]=> string(1) "1" }


Reproduce code:
---------------
$db_data_model='{"events":{"1":"film","0":"avatar"},"times":{"0":"2010-10-09 08:00","2":"2010-10-09 11:00","3":"2010-09-09"},"choices":{"1":["0","1"],"0":["0","1"]}}';
$model = json_decode($db_data_model);
$choices = (array)$model->choices;
var_dump($choices);
var_dump($choices['1']); // NULL
var_dump($choices[1]);   // NULL
var_dump($choices->{1}); // NULL
var_dump($choices->{'1'});//NULL

foreach ($choices as $k => $v) {
    var_dump($k, $v);
}



Expected result:
----------------
var_dump($choices['1']);

// array(2) { [0]=> string(1) "0" [1]=> string(1) "1" }

var_dump($choices['0']);

// array(2) { [0]=> string(1) "0" [1]=> string(1) "1" }

Actual result:
--------------
var_dump($choices['1']);

// NULL

var_dump($choices['0']);

// NULL

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-02-12 16:45 UTC] jani@php.net
RTFM:

http://php.net/array#language.types.array.casting

"If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible.."

And you could also access those directly without casting anyway, like this:

var_dump($model->choices->{1});



 [2010-02-12 18:48 UTC] nat at search dot ch
$choices is a variable of a new kind. It is no:
- Boolean
- Integer
- Floating point number
- String
- Array
- Object
It is an inconsequence with the rest of php.
I think this case should be considered in future versions.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Dec 04 17:00:01 2025 UTC