PHP Shorthand If Statement

A helpful little programming trick that I use from time to time is the shorthand if statement in PHP. I hope this tasty tidbit finds a place in your PHP tackle box.

By using a ternary operator in PHP, which is a shorthand comparison operator, you can greatly reduce the amount of code you need to write in your if / else statements.

basic shorthand if / else statement

$var = ($x==0) ? "true" : "false";

Instead of writing out:

if ($x==0) {
$var = "true";
} else {
$var = "false";
}

check for true value only

$var = ($x==0) ? "true" : "";

Which is the equivalent of:

if ($x==0) {
$var = "true";
}

handy usage

// Check a value and alter the string
// Place string in variable $movies to output later

$movies = "I " . ($corey > 0 ? "have" : "have not") . " seen Corey Feldman movies";

echo $movies;

You could also write it like this:

// Removing variable $movies
// Echoing the statement

echo "I " . ($corey > 0 ? "have" : "have not") . " seen Corey Feldman movies";

If the variable $corey is greater than 0, this would output: I have seen Corey Feldman movies. Otherwise it would output, I have not seen Corey Feldman movies.

As you can see, there are times when using the shorthand if statement makes sense. I find it most useful when I need to compare values and writing multiple lines of code will just complicate things.

 

Leave a Reply

Your email address will not be published. Required fields are marked *