PHP logical operators as expressions
I've successfully used this method to simplify code in various projects. Depends on case, but for most simple if/else conditionals I prefer to use this method (saves some lines).
Good
<?php
$array = [1, 2, 3, 4, 5];
if (!empty($array))
{
do_something();
}
Better
<?php
$array = [1, 2, 3, 4, 5];
empty($array) OR do_something();
More Examples
<?php
// $array['item'] is declared, lowercase it
isset($array['item']) AND $array['item'] = strtolower($array['item']);
// $array['item'] is NOT declared. Declare and assign a default value.
isset($array['item']) OR $array['item'] = 'Hello World!';
NOTE: use print() instead of echo(). print() construct behaves like a function, echo() does not.
<?php
$check = do_check();
// Doesn't work
$check AND echo 'Hello World!';
// Works
$check AND print 'Hello World!';
?>
Compare this case:
<input type="text" value="<?php $check AND print 'Hello World!' ?>" />
With using ternary operator:
<input type="text" value="<?php echo $check ? 'Hello World!' : NULL ?>" />
Written by Otar Chekurishvili
Related protips
7 Responses
This is really great. Thanks!
Yuck! Awful!
Using the operators this way will hinder the maintainability of the code.I'm sure it has it's place, but I don't think simplifying code is it.
Once again, it depends where you'll use this approach. For me it was a matter of time to get used to it.
nice syntax, but imho it's not really clear at first sight. An if is better.
I really love it in the template....too bad I'm not using php as a template language anymore :)
Or you could just use a one-line if which is more clear and can fit just as well in templating.
if (!empty($array)) do_something();
This is just an example of short-circuit evaluation in php, but as everyone has been saying, this will just damage the readability of your code, and also steps over the understanding of it. The boolean operators are intended to be used in conjunction with boolean evaluations, and not all of your operations evaluate to boolean, so they feel a bit out place. I won't deny the "cleverness", but if one of the programmers on my team shows me code with this syntax I'll say "very clever, now write it again".