Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Thing to Know About PHP Arrays

DZone's Guide to

Thing to Know About PHP Arrays

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, 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:

var_dump($arr);

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/

 

 

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}