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

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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/

 

 

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}