Reputation: 23062
I'm running through someone else's code, and they constantly avoid escaping their array keys.
For example:
$row_rsCatalogsItems[Name]
instead of
$row_rsCatalogsItems['Name']
so I'm constantly making tiny changes to everything I touch just to deal with that bit of laziness. But now I'm wondering whether there's even much benefit to doing so. I get that it'll check for constants before defaulting to a string (I detest that behavior in php when dealing with constants, since they validate to true even if not defined), but I'm not sure even that is worth the bother of changing all the many, many instances of constants-as-array-keys.
Suggestions?
Upvotes: 2
Views: 387
Reputation: 437336
There is more than one good reason.
Do
error_reporting(E_ALL);
in the beginning of your script and you will see all the reasons at once.
Fun aside, in practice you might think that well, this is something that I might get away with. And you could be right. But as a developer you have to draw the line somewhere about what is an acceptable hack and what is reason for verbal abuse. For me, this particular behavior is beyond that line.
The very immediate reason why this is bad is that it makes error_reporting(E_ALL)
unusable. And good development practice demands that all errors are reported, these notices are setting you up for buggier code and harder debugging sessions.
Update: I didn't address the issue of a practical solution to the existing situation, so here's what I would do in your shoes:
\[(a-zA-Z_-)\]
to ['$1']
(or something similar). If the number of replacements is equal to the number of notices in the log file, you are golden. Otherwise, try divide and conquer until you see where the regex is failing.Upvotes: 9
Reputation: 21368
I'd add the quotes. If nothing else, to ensure that:
Having said that, I understand that a programmer's time is valuable. Therefore, you can optionally out-lazy the lazy coder and use a regular expression like the following:
$input = '$row_rsCatalogsItems[Name]';
$str = preg_replace('/(\$[a-zA-Z_]+\[)([a-zA-Z]+)(\])/', '${1}\'${2}\'${3}', $input);
echo $str;
(You might want to step through the changes using that expression just to make sure you're changing the right things ;))
Upvotes: 1
Reputation: 8334
It's not technically correct to do it that way. You should probably use single quotes. It will use less cpu cycles and memory to run the code if you fix those. Will you notice a difference even if there are 1000 of those fixed in one file? Probably not.
If you fix it, it would be for correctness and not having warnings or notices, not really for speed or memory usage.
Upvotes: 2