n00b
n00b

Reputation: 16566

PHP improve a simple if/else statement

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

Any way to improve that?

Upvotes: 1

Views: 236

Answers (7)

n00b
n00b

Reputation: 16566

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?

Upvotes: 0

Manos Dilaverakis
Manos Dilaverakis

Reputation: 5869

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.

Upvotes: -1

Pepijn
Pepijn

Reputation: 4253

"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

Upvotes: 0

Christian Studer
Christian Studer

Reputation: 25617

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

Upvotes: 0

K. Norbert
K. Norbert

Reputation: 10684

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

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

echo $footer;

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382881

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 :(
}

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318748

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.

Upvotes: 2

Related Questions