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

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

<?php echo $var ?> 

but if, say, I do not pass the variable $ var, I get a nasty

 <h4>A PHP Error was encountered</h4> 

in my html source code. I worked with django before the template, if the variable does not exist, they simply do not display it. Is there a way in php / codeigniter to say "if $ var exists, something else does nothing"?

I tried:

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

but it was a mistake. Thanks!

+6
source share
3 answers

Use the isset() function to check if a variable is declared.

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

Use the empty() function to check for a variable such as NULL, "", false or 0 .

+15
source

You can use the ternary operator

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

I am creating a new helper function (see https://www.codeigniter.com/userguide2/general/helpers.html ) called 'exists', which checks if the isset variable is not empty:

 function exists($string) { if (isset($string) && $string) { return $string; } return ''; } 

Include this in the controller:

 $this->load->helper('exists'); 

Then in the view, I only have:

 <?php echo exists($var) ?> 

If you would like, you could put the echo right into the function, but not sure if this is bad practice?

0
source

Source: https://habr.com/ru/post/895301/


All Articles