Access array element indexed by numerical string

前端 未结 4 1317
有刺的猬
有刺的猬 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条回答
  •  梦毁少年i
    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]."
    "; echo $array['1']."
    "; echo $array["1"]."
    "; echo $array[(string)1]."
    "; echo $array[$key]."
    ";

    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);
    

提交回复
热议问题