PHP - How can I write better code with E_NOTICES enabled?
Question
I prefer to develop with E_NOTICES turned on, but I often have to write excess, overly verbose, code when working with array indexes. How can I write this code in less code with E_NOTICES enabled.
With notices suppressed
if ($_REQUEST['some_key'] == 'bob')
{
}
Without notices suppressed
if (array_key_exists('some_key', $_REQUEST) && $_REQUEST['some_key'] == 'bob')
{
}
Solution
I generally use isset()
, instead of array_key_exists()
, for that kind of thing ; which means using something like this :
if (isset($_REQUEST['some_key']) && $_REQUEST['some_key'] == 'bob')
{
}
A couple of differences :
isset
is a language construct, and not a function -- and its faster (no function call)- note that
isset
will returnfalse
if a data isnull
;array_key_exists
will returntrue
- But it's often not a problem, especially when dealing with GET/POST parameters
- it shorter to write (a couple less characters)
- and you can use something like
if (isset($_REQUEST['a'], $_REQUEST['b'], $_REQUEST['c'])
, if necessary
- and you can use something like
OTHER TIPS
The easy way out is to use @
for error suppression:
if (@$_REQUEST['some_key'] == 'bob') {}
However, this can be very slow if you're using it more than once or twice per page load.
Another solution is to assign your unknown by reference (although I'm not 100% sure this will work for superglobals like $_REQUEST
):
$some_key =& $_REQUEST['some_key'];
if ($some_key == 'bob') {}
Generally, I just use isset
like Pascal said.