We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.
<input value='<?php if(isset($var)){print($var);}; ?>'>
How can I write this shorter? I'm okay introducing a new function like this:
<input value='<?php printvar('myvar'); ?>'>
But I don't succeed in writing the printvar() function.
For PHP >= 5.x:
My recommendation would be to create a
issetor
function:This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:
But also use it in other cases:
For PHP >= 7.0:
As of PHP 7 you can use the null-coalesce operator:
Or in your usage: