Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $foo[bar] and $foo['bar'] in php

I've been using $foo[bar] on a lot of project without noticing the missing '

Nowadays, I understand why it works, I assume it is because of a missing constant being replaced by it's name, thus referring to exactly the same array item.

But.. Is it very wrong or can it be accepted. What are the downsides? Should I dig in old projects to replace this or is the performance drop on this really not noticeable?

like image 394
Vincent Duprez Avatar asked Jan 11 '23 06:01

Vincent Duprez


2 Answers

What are the downsides?

Say you have a URL like http://somesite.com/test.php?item=20 ,

Scenario:1 (Your case)

<?php
echo $_GET[item]; // 20 is printed with a warning.. 

Scenario:2 (The worst case)

<?php
define('item',20);
echo $_GET[item]; // A warning will be thrown and nothing will be printed.

Should I dig in old projects to replace this or is the performance drop on this really not noticeable?

I recommend you do it.

like image 54
Shankar Narayana Damodaran Avatar answered Jan 16 '23 21:01

Shankar Narayana Damodaran


If you have turned on your error displaying then you can find notices like

Notice: Use of undefined constant bar - assumed 'bar' in [...][...] on line

this if you used it like $foo[bar]

You can see the difference if execute the following code

$arr1 = array(1=>1);
$arr2 = array(a=>2);
$arr3 = array('a'=>3);

print_r($arr1);
print_r($arr2);
print_r($arr3);

But its recomnded to use it with single quotes if the key of your array is a string because warnings will cause performance drop..

like image 23
Deepu Avatar answered Jan 16 '23 20:01

Deepu