Access php arrays with explicit strings as index

I know that it is more efficient to use "restricted strings" rather than "..."

but I was wondering if there is a performance improvement with this


$a = array( 'table' => 'myTable', 'order' => 'myOrder' );

$table = $a['table']

instead


$a = array( table => 'myTable', order => 'myOrder' );

$table = $a[table]

I think so, but just wanted to know your opinion ...

+3
source share
3 answers

Yes. In your second example, the PHP processor checks to see if the "table" is defined as a constant before changing it to an array key, so it does one more check than necessary. It can also be a problem.

Consider this:

const table = 'text';

$a = array( table => 'myTable', order => 'myOrder' );

$table = $a[table]

Now PHP interprets your array as $ a [text], which is not what you want.

+8
source

. PHP table order , table order , PHP "table" "order".

+5

The difference, according to the study, between the "string" and the "string" is so insignificant that it does not exist. Not that it matters, BUT it's faster to do

echo "this is {$var1} and {$var2} and {$var3}";

than

echo 'this is ' . $var1 . ' and ' . $var2 . ' and ' . $var3;
+1
source

Source: https://habr.com/ru/post/1703322/


All Articles