If I want to repopulate a form with the $_POST values for example (there are other applications for this problem, but that's the easiest) I have to always check if the $_POST index is set, before I can use it's value, or I'll get the NOTICE from php.
For example:
echo '<input type="text" name="somefield" value="';
if(isset($_POST['somefield']))
{ echo $_POST['somefield']; }
echo '">';
With complex forms, this seems cumbersome and like a lot of repetition. So I thought, let's extract a function:
function varcheck_isset($vartocheck)
{
if(isset($vartocheck))
{return $vartocheck;}
else
{return '';}
}
and then do
echo '<input type="text" name="somefield" value="';
echo varcheck_isset($_POST['somefield']);
echo '">';
Makes the code nicer.
But when I do this and $_POST['somefield'] is not set, it says
Notice: Undefined index: somefield
:-(
Anybody got an idea or suggestions how to make this work?
EDIT:
Here's what I ended up doing - I accepted Organgepill's answer, just modified it slightly:
function arraycheck_isset($arraytocheck, $indextocheck)
{
if(isset($arraytocheck) && is_array($arraytocheck) && array_key_exists($indextocheck, $arraytocheck))
{ return $arraytocheck[$vartocheck];}
else
{ return '';}
}
The comment below by elclanrs was also pretty good. just write:
echo $_POST['field'] ?: '';
Personally I like the non-shorthand version better though, because I may also have cases where I need to check for other things, besides isset() - for example a regex. This way I keep it consistent by going through a function each time.