如何在codeigniter(php)中检查变量是否存在?新问题

时间:2023-01-01 16:28:03

Hey I'm new to php and codeigniter. I know that in codeigniter's view you can echo a variable like

嘿,我是php和codeigniter的新手。我知道在codeigniter的视图中你可以回显像这样的变量

<?php echo $var ?>

but if say, I don't pass the variable $var, I get a nasty

但如果说,我没有传递变量$ var,我得到一个令人讨厌的

<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' ?

在我的HTML源代码中。我在模板之前使用过django,如果变量不存在,它们就不会渲染它。有没有办法在php / codeigniter中说'如果$ var存在,那么其他什么都不做'?

I tried:

我试过了:

<?php if($title): ?>
    <?php echo $title ?>
<?php endif; ?>

but that was an error. Thanks!

但这是一个错误。谢谢!

3 个解决方案

#1


15  

Use the isset() function to test if a variable has been declared.

使用isset()函数测试是否已声明变量。

if (isset($var)) echo $var;

Use the empty() function to test if a variable has no content such as NULL, "", false or 0.

使用empty()函数测试变量是否没有NULL,“”,false或0等内容。

#2


0  

You could use the ternary operator

您可以使用三元运算符

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

#3


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:

我创建了一个名为'exists'的新辅助函数(参见:https://www.codeigniter.com/userguide2/general/helpers.html),它检查变量是否设置为非空:

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?

如果你想要你可以将回声直接放在函数中,但不确定这是不好的做法?

#1


15  

Use the isset() function to test if a variable has been declared.

使用isset()函数测试是否已声明变量。

if (isset($var)) echo $var;

Use the empty() function to test if a variable has no content such as NULL, "", false or 0.

使用empty()函数测试变量是否没有NULL,“”,false或0等内容。

#2


0  

You could use the ternary operator

您可以使用三元运算符

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

#3


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:

我创建了一个名为'exists'的新辅助函数(参见:https://www.codeigniter.com/userguide2/general/helpers.html),它检查变量是否设置为非空:

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?

如果你想要你可以将回声直接放在函数中,但不确定这是不好的做法?