tags:

views:

5478

answers:

8

What is the difference, if any, between these methods of indexing into a PHP array:

$array[$index]
$array["$index"]
$array["{$index}"]

I'm interested in both the performance and functional differences.

Update:

(In response to @Jeremy) I'm not sure that's right. I ran this code:

  $array = array(100, 200, 300);
  print_r($array);
  $idx = 0;
  $array[$idx] = 123;
  print_r($array);
  $array["$idx"] = 456;
  print_r($array);
  $array["{$idx}"] = 789;
  print_r($array);

And got this output:

Array ( [0] => 100 [1] => 200 [2] => 300 )

Array ( [0] => 123 [1] => 200 [2] => 300 )

Array ( [0] => 456 [1] => 200 [2] => 300 )

Array ( [0] => 789 [1] => 200 [2] => 300 )

A: 

If $index is a string there is no difference because $index, "$index", and "{$index}" all evaluate to the same string. If $index is a number, for example 10, the first line will evaluate to $array[10] and the other two lines will evaluate to $array["10"] which is a different element than $array[10].

yjerem
A: 

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

Another variation that I use sometimes when I have an array inside a string is:

$str = "this is my string {$array["$index"]}";

Edit: What I meant to say is $row[’id’] is faster than $row[id]

ejunker
A: 

Response to the Update:

Oh, you're right, I guess PHP must convert array index strings to numbers if they contain only digits. I tried this code:

 $array = array('1' => 100, '2' => 200, 1 => 300, 2 => 400);
 print_r($array);

And the output was:

 Array([1] => 300 [2] => 400)

I've done some more tests and found that if an array index (or key) is made up of only digits, it's always converted to an integer, otherwise it's a string.

ejunker:

Can you explain why that's faster? Doesn't it take the interpreter an extra step to parse "$index" into the string to use as an index instead of just using $index as the index?

yjerem
+6  A: 

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.

Please, no the string myth again! There's no measurable speed difference between use of one or another kind of strings. Even if there was, strings are parsed once program is loaded, and not reparsed in loops, so it's all moot.
porneL
as much as I agree with your aversion to micro optimisation porneL, some strings need to be reinterpreted in a loop, e.g.:$x = array("w", "y", "x", "z");for ($i = 0; $i < 100; $i++){ echo "hello world {$x[$i%4]}\n";}
Antony Carthy
+10  A: 

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.)

svec
Knowledge Craving
+1  A: 

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
yjerem
+2  A: 

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.

Akira
+3  A: 

On a bit of a side note, $array[$index] does not produce any notices/warnings where $array[3] will throw a message (notice level I think) about 3 being an undefined constant.

That is absolutely not true.

Akira
This should be a comment.
WCWedin
@WCWedin we didn't have comments back then
yjerem
Touche, good sir.
WCWedin