Single Line If…Else Statement

You undoubtedly are familiar with using if…else (if else) statements in your PHP programming. Are you also aware that for simple if…else needs (e.g., only needing to set one variable) you can get by using only one line of code?

The basic format of the one line if…else statement is:

$variable = (if statement) ? if true code : if false code;

Let’s illustrate with an example. Occasionally, you might want to set a select list item to be the default selected option. Using a posted variable for the select field in question, you could use a standard if…else like:

if ($_POST["variable"] == $something) {
   $selected = " selected = 'selected'";
} else {
   $selected = "";

Then this could be used in an option statement, like:

echo "<option value='".$variable."'".$selected.">".$variable."</option>n";

To replace the 5 if…else lines above, we could use the following one line:

$selected = ($_POST["variable"] == $something) ? " selected=' selected'" : "";

Like this content? Why not share it?
Share on FacebookTweet about this on TwitterShare on LinkedInBuffer this pagePin on PinterestShare on Redditshare on TumblrShare on StumbleUpon
There Are No Comments
Click to Add the First »