-1

I've got two quick questions which I can't find on Google.

What's the correct name for this operator?

$a = ($b > 5) ? 'High' : 'Low';

And secondly, is there ever a situation when it's preferable over any other operator? I know 'if else' is a faster method and is easier to read and edit.

Thank you!

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Tom
  • 207
  • 2
  • 18
  • I don't know about faster, but at least that is objective. Easier to read and edit obviously are not. – Jon Jul 05 '13 at 19:42

2 Answers2

3

It is called the Ternary operator.

This person did some benchmarks, and the answer is that it depends on the situation.

Quoting from this doc:

// snippet 1
$tmp = isset($context['test']) ? $context['test'] : '';

// snippet 2
if (isset($context['test'])) {
    $tmp = $context['test'];
} else {
    $tmp = '';
}

The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.

jh314
  • 27,144
  • 16
  • 62
  • 82
  • I don't think it's wise to trust the blog you posted; my own performance benchmarks don't put the counts anywhere near what he says, and his comments about PHP's copying method are outdated at best. [*Here is the performance running on 5.2.5*](http://codepad.org/EToVfPH7), and I got even more equal performance on 5.3.13. – Cat Jul 05 '13 at 20:06
0

It's called ternary operator.

It's used for making your code simpler, and it sometimes helps you to combine two statements into just one.

Here goes an example. Instead of:

if($Disabled) $String = 'disabled'; else $String = '';
echo '<input type="text" ' . $String . '>';

You can use:

echo '<input type="text" ' . $Disabled ? 'disabled' : '' . '>';

I didn't simplify the code above on purpose, to clearly show my point. This way you have just one statement, avoiding the extra if / else. In some situations, it may help you. In others, you will see no benefit.

Marcovecchio
  • 1,322
  • 9
  • 19