Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"]

Tags:

syntax

php

People also ask

How many types of array indexing is possible in PHP?

Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

How do you get the index of an element in an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.

What is PHP indexed array?

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

What is an array indexing?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.

Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).

Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.

In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.


I timed the 3 ways of using an index like this:

for ($ii = 0; $ii < 1000000; $ii++) {
   // TEST 1
   $array[$idx] = $ii;
   // TEST 2
   $array["$idx"] = $ii;
   // TEST 3
   $array["{$idx}"] = $ii;
}

The first set of tests used $idx=0, the second set used $idx="0", and the third set used $idx="blah". Timing was done using microtime() diffs. I'm using WinXP, PHP 5.2, Apache 2.2, and Vim. :-)

And here are the results:

Using $idx = 0

$array[$idx]            // time: 0.45435905456543 seconds
$array["$idx"]          // time: 1.0537171363831 seconds
$array["{$idx}"]        // time: 1.0621709823608 seconds
ratio "$idx" / $idx     // 2.3191287282497
ratio "{$idx}" / $idx   // 2.3377348193858

Using $idx = "0"

$array[$idx]            // time: 0.5107250213623 seconds
$array["$idx"]          // time: 0.77445602416992 seconds
$array["{$idx}"]        // time: 0.77329802513123 seconds
ratio "$idx" / $idx     // = 1.5163855142717
ratio "{$idx}" / $idx   // = 1.5141181512285

Using $idx = "blah"

$array[$idx]           // time: 0.48077392578125 seconds
$array["$idx"]         // time: 0.73676419258118 seconds
$array["{$idx}"]       // time: 0.71499705314636 seconds
ratio "$idx" / $idx    // = 1.5324545551923
ratio "{$idx}" / $idx  // = 1.4871793473086

So $array[$idx] is the hands-down winner of the performance competition, at least on my machine. (The results were very repeatable, BTW, I ran it 3 or 4 times and got the same results.)


I believe from a performance perspective that $array["$index"] is faster than $array[$index] See Best practices to optimize PHP code performance

Don't believe everything you read so blindly... I think you misinterpreted that. The article says $array['index'] is faster than $array[index] where index is a string, not a variable. That's because if you don't wrap it in quotes PHP looks for a constant var and can't find one so assumes you meant to make it a string.


When will the different indexing methods resolve to different indices?

According to http://php.net/types.array, an array index can only be an integer or a string. If you try to use a float as an index, it will truncate it to integer. So if $index is a float with the value 3.14, then $array[$index] will evaluate to $array[3] and $array["$index"] will evaluate to $array['3.14']. Here is some code that confirms this:

$array = array(3.14 => 'float', '3.14' => 'string');
print_r($array);

$index = 3.14;
echo $array[$index]."\n";
echo $array["$index"]."\n";

The output:

Array([3] => float [3.14] => string)
float
string