开发者

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

开发者 https://www.devze.com 2023-03-28 17:59 出处:网络
Hey I\'m new to php and codeigniter.I know that in codeigniter\'s view you can echo a variable like <?php echo $var ?>

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?


You could use the ternary operator

echo isset($var) ? $var : '';


I had a similar noob question of:

How to check if a variable is set to null, undefined or 0. But allow the 0 option?

I landed here and refactored some of the answers into this:

if (empty($a) && $a != 0)

Which passed testing for my case.

0

精彩评论

暂无评论...
验证码 换一张
取 消