php - How to simplify if isset $var else $var = ' '; -
if want repopulate form $_post values example (there other applications problem, that's easiest) have check if $_post index set, before can use it's value, or i'll notice php.
for example:
echo '<input type="text" name="somefield" value="'; if(isset($_post['somefield'])) { echo $_post['somefield']; } echo '">'; with complex forms, seems cumbersome , lot of repetition. thought, let's extract function:
function varcheck_isset($vartocheck) { if(isset($vartocheck)) {return $vartocheck;} else {return '';} } and do
echo '<input type="text" name="somefield" value="'; echo varcheck_isset($_post['somefield']); echo '">'; makes code nicer.
but when , $_post['somefield'] not set, says
notice: undefined index: somefield
:-(
anybody got idea or suggestions how make work?
edit:
here's ended doing - accepted organgepill's answer, modified 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 elclanrs pretty good. write:
echo $_post['field'] ?: ''; personally non-shorthand version better though, because may have cases need check other things, besides isset() - example regex. way keep consistent going through function each time.
try this:
function postedval($vartocheck) { if(array_key_exists($vartocheck, $_post)) return $_post["$vartocheck"]; return ''; } your function hitting first case because checking if parameter set have been if (isset($_post[$vartocheck]))
Comments
Post a Comment