Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for variable existence in codeigniter(php)? newb question

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!

like image 433
Derek Avatar asked Aug 18 '11 06:08

Derek


2 Answers

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.

like image 100
Kaken Bok Avatar answered Nov 11 '22 18:11

Kaken Bok


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?

like image 1
martinedwards Avatar answered Nov 11 '22 18:11

martinedwards