开发者

PHP improve a simple if/else statement

开发者 https://www.devze.com 2022-12-30 01:53 出处:网络
<?php echo isset($areas[\'footer\']) ? $areas[开发者_JS百科\'footer\'] : null; ?> Any way to improve that?Note that you are echoing and in false condition it would be null which does not have
<?php echo isset($areas['footer']) ? $areas[开发者_JS百科'footer'] : null; ?>

Any way to improve that?


Note that you are echoing and in false condition it would be null which does not have any effect. You could say like 'empty' or ' ' or 'not found' instead. Other alternative is to get the return value of isset:

$return = isset($areas['footer']) ? $areas['footer'] : null;

if ($return)
{
  // $return contains footer info
}
else
{
  // footer was not set :(
}


Depending on where $areas comes from it might be cleaner to assign it to a variable:

$footer = isset($areas['footer']) ? $areas['footer'] : null;

Then you can use $footer without any additional isset checks.


You can also spare the else branch, by setting a default:

$footer = null;
if (isset($areas['footer'])) {
  $footer = $areas['footer'];
}

echo $footer;


No, this is the most concise way of handling this sort of output.


"i'm using this kind of code very often"

Maybe you should avoid the issue altogether by using a template language, or encapsulating this behavior in a function?

like this:

function get_area($area) {
    if... //your code
    return $area


One shorter version i can think of would be:

<?php !isset($areas['footer']) or print $areas['footer']; ?>

But i'm not sure if it is faster or more elegant. What do you guys think?


echo $areas['footer'];

Simple and has the exact same effect as the original line.

Edit in reply to Felix This gives a notice, but unless you're supposed to turn this in as ultra-perfect homework, it doesn't really matter. You can either fill your code with isset calls or ignore small stuff like this. I'd worry about it if I was working in say... Java, but pragmatically nobody is going to care if PHP code that works produces notices.

0

精彩评论

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

关注公众号