Hey I'm new to php and codeigniter. I know that in codeigniter's view you can echo a variable like
<?php echo $var ?>
but if say, I don't pass the variable $var, I get a nasty
<h4>A PHP Error was encountered</h4>
in my html source code. I've worked with django before an in their template, if the variable doesn't exist, they simply don't render it. Is there a way in php/codeigniter to say 'if $var exists do smthing else do nothing' ?
I tried:
<?php if($title): ?>
<?php echo $title ?>
<?php endif; ?>
but that was an error. Thanks!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With