tags:

views:

138

answers:

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

Any way to improve that?

+3  A: 

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 :(
}
Sarfraz
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!
n00b
@booze2go: You are welcome :)
Sarfraz
+2  A: 

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.

ThiefMaster
A: 
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.

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

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

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

echo $footer;
WishCow
A: 

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

christian studer
A: 

"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
Pepijn
Ironically, PHP is a templating language, though it's often not used that way, since things like "real template languages" such as Smarty exist.
Andrew Gwozdziewycz
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.
Pepijn
A: 

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?

n00b