by snorkel · 15y ago · 0 comments
$foo = $_POST["foo"];
Undefined array key! Oh, no! Tragedy! A crime has been committed! Are you kidding? Just set $foo to undefined and let me deal with the consequences, please?I fundamentally disagree with you though. For me, notices are very useful for identifying typos and other coding mistakes that can lead to incorrect behavior.
Consider the following lines of code:
$user_info = array(
'id' => 1,
'username' => 'nbpoole',
'is_guess' => false
);
if (!$user_info['is_guest'])
{
echo 'Member stuff';
}
When I run that script with error_reporting set to E_ALL, I get an "undefined index" notice pointing me to the line where I do the comparison: at that point, I can track down where in my code I misspelled the word guest. Without the notice, I might not immediately realize that the 'is_guest' index was mis-spelled somewhere. $val = array_key_exists('key', $dict) ? $dict['key'] : NULL;
Being able to say "I expect a potentially nil value (and am okay with that)" via get() rather than array index is both semantically useful, and far more beautiful than the PHP equivalent.Python's dict.get is a bit like the getOrElse found in Scala. It's quite handy and can be seen as advanced conceptually.
I actually added some code like that to a recent post about PHP here: http://news.ycombinator.com/item?id=2771304
Ever tried to assign a non-existing variable in another language? I think you will get a compile error.
This isn't too hard:
$foo = isset($_POST["foo"]) ? $_POST["foo"] : null;