How does PHP index associative arrays?

后端 未结 3 1464
囚心锁ツ
囚心锁ツ 2020-12-03 22:59

As I know, in associative arrays, if the keys is not set, it will be set automatically. But it seem doesn\'t make sense in this case:

$a = array         


        
3条回答
  •  感情败类
    2020-12-03 23:32

    @Uchiha is right, just as an include to that answer, if you want to avoid this problem, keep members of an array (which are not having keys specified) at the last


    $a = array( '1' => 'One', '3', '2' => 'Two');
    

    will dump

    array (size=2)
      1 => string 'One' (length=3)
      2 => string 'Two' (length=3)
    


    and keeping members with undefined keys at last

    $a = array( '1' => 'One', '2' => 'Two', '3');
    

    will dump

    array (size=3)
      1 => string 'One' (length=3)
      2 => string 'Two' (length=3)
      3 => string '3' (length=1)
    


    will avoid issues you are facing.

提交回复
热议问题