Priti's Technical Corner

October 1, 2011

PHP 5.3: Array

Filed under: PHP, PHP Array — Tags: — pritisolanki @ 5:04 am

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 !

Advertisements

1 Comment »

  1. 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 :-)!!";

    Comment by Nikhil — November 11, 2011 @ 6:16 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: