Thing to Know About PHP Arrays

Consider the following case. We have an array with identical keys.

$arr = array(1 => 10, 1 => 11);

What happens when the interpreter reaches this line of code? This is not a syntax error and it is completely valid. Very similar, but more interesting case is when we have an array of identical keys, where those identical keys are represented once as an integer and then as a string.

Keys in PHP arrays are not type sensitive, so pay attention when using them!
Keys in PHP arrays are not type sensitive, so pay attention when using them!

$arr = array(1 => 10, "1" => 11);

Now several questions arise. First of all, how many elements have this array? Two or one. This can be easily verified by checking what count() will return.

echo count($arr);

The correct answer is 1. This simply means, that there’s no difference between string keys and integer keys. What would happen if we had a “normal” array with different keys?

$arr = array(1 => 10, "2" => 11);
echo count($arr);

As expected this returns 2.

Next thing to check is what’s in the array after this initialization line.

$arr = array(1 => 10, "1" => 11);

Is there something in the first element $arr[0], or there’s something in the second element $arr[1]? What is the value of the single value?
As it appears the second element replaces the first one. We’ve seen that the array has only one value, but where’s that value? The only way to check this is to dump both elements:


Here we can see that $arr[1] contains “11” and it is the only value, and $arr[0] is not set.

Leave a Reply

Your email address will not be published. Required fields are marked *