1
<?php echo isset($areas['footer']) ? $areas['footer'] : null; ?>

Any way to improve that?

7 Answers 7

4

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 :(
}
Sign up to request clarification or add additional context in comments.

1 Comment

okay... i thought so but wanted to be sure since i'm using this kind of code very often and just wanted to see if there's something to improve. thank you!
2

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.

Comments

0

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

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

echo $footer;

Comments

0

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

Comments

0

"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

2 Comments

Ironically, PHP is a templating language, though it's often not used that way, since things like "real template languages" such as Smarty exist.
I knew someone was going to say that. I never used a template language with PHP, but I think PHP does a lousy job at being a proper template language.
0

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?

Comments

-1
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.

3 Comments

But it will give you a notice/warning (not sure which) if $areas has not element with key footer.
The prefix it with @ to silence it.
@Pepijin: Silencing a warning instead of fixing the condition that caused it is usually considered bad coding style.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.