Access array element indexed by numerical string

前端 未结 4 1300
有刺的猬
有刺的猬 2020-12-30 04:52

I have encountered something odd.

I have a php array, indexed with numerical keys. However it appears impossible to access any of the elements because php automatica

相关标签:
4条回答
  • 2020-12-30 05:02

    String keys containing valid integer values would be cast to integer keys automatically in “normal” array creation – but it seems casting from object to array doesn’t apply the same logic.

    It can be fixed however, by using

    $array = array_combine(array_keys($array), array_values($array));
    

    after your line that creates the array from the object. http://codepad.viper-7.com/v5rGJa


    Although, same as Dave already said in his comment, using get_object_vars looks like a “cleaner” solution to me as well.

    0 讨论(0)
  • 2020-12-30 05:07
    foreach ($array as $key => $value){
        var_dump($key);
        var_dump($value);
    }
    

    shows

    string(1) "1"
    string(3) "one"
    

    But echo $array['"1"']; gives

    E_NOTICE :  type 8 -- Undefined index: "1" -- at line 8
    

    That's strange!

    0 讨论(0)
  • 2020-12-30 05:17

    Unbelievable but this is normal behavior in php, it was considered as a bug (link) in the year 2008.

    But they just pointed out to the manual for the cast with (array):

    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;

    You can use get_object_vars() instead:

    $object = new stdClass();
    $object->{'1'} = 'one';
    
    $array = get_object_vars( $object );
    
    $key = '1';
    echo $array[1]."<br>";
    echo $array['1']."<br>";
    echo $array["1"]."<br>";
    echo $array[(string)1]."<br>";
    echo $array[$key]."<br>";
    

    Doesn't explain why this happens, but is a solution to avoid the cast problem.

    Off topic but I thought maybe it is interesting. Found this in the manual.

    To avoid these kind of problems, always use an integer OR a string as index, don't mix it up and don't use integers in a string.

    Example of mixed array:

    $array = array(
        1    => "a",
        "1"  => "b",//overrides 1
        1.5  => "c",//overrides "1"
        true => "d",//overrides 1.5
    );
    
    var_dump($array);
    
    0 讨论(0)
  • 2020-12-30 05:17

    You can use

    $vars  = get_object_vars($object);
    echo $vars[1];
    
    0 讨论(0)
提交回复
热议问题