How to check for variable existence in codeigniter(php)? newb question
Use the isset()
function to test if a variable has been declared.
if (isset($var)) echo $var;
Use the empty()
function to test if a variable has no content such as NULL, "", false or 0
.
I create a new helper function (See: https://www.codeigniter.com/userguide2/general/helpers.html) called 'exists' that checks if the variable isset and not empty:
function exists($string) { if (isset($string) && $string) { return $string; } return '';}
Include that in the controller:
$this->load->helper('exists');
Then in the view I just have:
<?php echo exists($var) ?>
If you wanted you could put the echo straight in the function, but not sure if that's bad practice?