Over a million developers have joined DZone.

Thing to Know About PHP Arrays

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Related posts:

  1. PHP: What is More Powerful Than list() – Perhaps extract()
  2. PHP: What is More Powerful Than list()
  3. PHP: The Array Element Doesn’t Exist – Suppress the Warnings


Source: http://www.stoimen.com/blog/2011/10/19/thing-to-know-about-php-arrays/



Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}