Many new PHP programmers are not aware that they need to quote array keys if they are strings. All too often you will see code that looks like follows.
$userAgent = $_SERVER[HTTP_USER_AGENT];
This is wrong. It does end up working, but please allow me to explain why it is working and just how ugly the process is. If you do not have test code readily available to follow along with, feel free to use the above.
You are most likely to fall into habit of doing this because you are not aware of the notice-level error that occurs. Please make sure that you are familiar with how to report all errors in PHP.
Once you have modified your script to report all errors, try executing it again. You will get an error that reads something like the following.
Notice: Use of undefined constant HTTP_USER_AGENT - assumed 'HTTP_USER_AGENT' in /home/eric/localhost/badkey.php on line 3
What PHP has done is correctly thought you were referring to a constant. If you are not familiar with constants in PHP, please read about them on php.net. The designers of PHP decided that if you refer to a constant that has not been defined, the constant's name will instead be treated as a string.
So, a notice-level error and a lucky presumption by the PHP engine later, the above code is translated to this equivalent.
$userAgent = $_SERVER['HTTP_USER_AGENT'];
Why should we not just write it as that in the first place and avoid this messy process? There is no reason. Just quote your string keys and both you and the PHP engine will be happier. How nasty would this have been if there was actually an HTTP_USER_AGENT constant defined with a value you would not be expecting at all?
Remember to always keep your PHP code error-free!
0 Responses to PHP Programmers: Quote Your String Keys!
Leave a Reply