I was trying to understand behavior of following code in php 5.3
<?php
$arr=array(’1′=>’a',1=>’b',’C',2=>’D');
echo count($arr);
?>
Output: 2
I couldn’t understand till I explored more in PHP manual. When you print this array you will see
array(1=>’b',2=>’D');
Why !!
In PHP, 1 and ’1′ is equal and we know the later index overwrite the previous hence, it’s 1=>b .Now, why 2=>’D', because
the next highest index is 2 so C index will be 2 hence, 2=>’D’
Still struggling to understand see following
$arr=array(‘a’=>’b',’C',2=>’D');
index 0 will be assigned to C
$arr=array(‘a’=>’b',2=>’C',’D');
index 3 will be assigned to D
numerical index will start from the highest integer.
In case 1, 2=>’D’ is defined after C hence index starts with zero where as,
in later case index is already set and next highest will result 3=>’D’
Hope you find this interesting !
Tags: php array
November 11, 2011 at 6:16 am
Hey Priti,
This is interesting stuff …. but mostly non-standard implementation of data types…. hopefully this behavior is consistant atleast. See the following snippet..
<?php
$a='1.2';
$b=1.2;
if($a==$b)
echo "We are equals…ohh really?? ";
if($a!==$b)
echo "But we are not identical…oh yes, we are not!!! ";
echo "This is becoz php is loosely (lousily) typed language!! so they brought === in defense
!!";