PHP - How can I write better code with E_NOTICES enabled?
I prefer to develop with E_NOTICES enabled, but I often find myself writing redundant, overly verbose code when dealing with array indices. How can I write this code less code with E_NOTICES enabled.
When suppressing notifications
if ($_REQUEST['some_key'] == 'bob')
{
}
With no warning suppressed
if (array_key_exists('some_key', $_REQUEST) && $_REQUEST['some_key'] == 'bob')
{
}
a source to share
I usually use instead , for this kind of thing; which means using something like this: isset()
array_key_exists()
if (isset($_REQUEST['some_key']) && $_REQUEST['some_key'] == 'bob')
{
}
Several differences:
-
isset
is a language construct, not a function - and its faster (no function call) - note what
isset
will returnfalse
if datanull
;array_key_exists
will returntrue
- But this is often not a problem, especially when dealing with GET / POST parameters.
- it's shorter to write (a couple less characters)
- and you can use something like
if (isset($_REQUEST['a'], $_REQUEST['b'], $_REQUEST['c'])
if needed
- and you can use something like
a source to share
An easy way out is to use @
to suppress errors:
if (@$_REQUEST['some_key'] == 'bob') {}
However, it can be very slow if you use it more than one or two times per page load.
Another solution is to assign your unknown by reference (although I'm not sure if 100% this will work for super valves like $_REQUEST
):
$some_key =& $_REQUEST['some_key'];
if ($some_key == 'bob') {}
Generally, I just use isset
like Pascal said.
a source to share