Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

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

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
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 " " or "", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...