非关联数组与关键字数组之间的区别,其中键是字符串整数

非关联数组与关键字数组之间的区别,其中键是字符串整数

问题描述:

Are the following three arrays identical, or can they be told apart? If so, how?

$array1=array('abc','def','ghi');
$array2=array('0'=>'abc','1'=>'def','2'=>'ghi');
$array3=array(0=>'abc',1=>'def',2=>'ghi');

以下三个数组是相同的,还是可以分开? 如果是这样,怎么做? p>

  $ array1 = array('abc','def','ghi'); 
 $ array2 = array('0'=>  'ABC', '1'=> '高清', '2'=> 'GHI'); 
 $的ARRAY3 =阵列(0 => 'ABC',1 => '高清',2 =  >'ghi'); 
  code>  pre> 
  div>

A simple test would have prevented this confusion for you.

<?php

$array1=array('abc','def','ghi');
$array2=array('0'=>'abc','1'=>'def','2'=>'ghi');
$array3=array(0=>'abc',1=>'def',2=>'ghi');

print_r($array1);
print_r($array2);
print_r($array3);

Output

Array
(
    [0] => abc
    [1] => def
    [2] => ghi
)
Array
(
    [0] => abc
    [1] => def
    [2] => ghi
)
Array
(
    [0] => abc
    [1] => def
    [2] => ghi
)

Do you see any difference? None whatsoever.

Are the following three arrays identical, or can they be told apart?

Yes they are identical and no they cannot be told apart.

Note this example from PHP.net

<?php
$array = array(
    1    => "a",
    "1"  => "b",
    1.5  => "c",
    true => "d",
);
var_dump($array);
?> 

Read this

As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over.

That means your 0 and "0" mean the same thing, the end :)

They are not identical because you can call the first one by $array1[0] and will output "abc". The second one the key has to be not in quotes or else it will think it is a string. $array2["0"] will output "abc" and $array[0] will too. The third one is identical with the first one though, since the key is provided without quotes. $array[3] will output "abc".

They appear the same to me, both in data and functionality:

<?php

$array1=array('abc','def','ghi');
$array2=array('0'=>'abc','1'=>'def','2'=>'ghi');
$array3=array(0=>'abc',1=>'def',2=>'ghi');

var_dump($array1); // array(3) { [0]=> string(3) "abc" [1]=> string(3) "def" [2]=> string(3) "ghi" } 

var_dump($array2); // array(3) { [0]=> string(3) "abc" [1]=> string(3) "def" [2]=> string(3) "ghi" } 

var_dump($array3); // array(3) { [0]=> string(3) "abc" [1]=> string(3) "def" [2]=> string(3) "ghi" }

echo $array1[0]; // abc
echo $array1['0']; // abc
echo $array2[0]; // abc
echo $array2['0']; // abc
echo $array3[0]; // abc
echo $array3['0']; // abc

array_push($array2, 'jik');

var_dump($array2); // array(4) { [0]=> string(3) "abc" [1]=> string(3) "def" [2]=> string(3) "ghi" [3]=> string(3) "jik" }

?>