Menu

How can I be a good
WEB ADMINISTATOR?

PHP If/Else Statement Inline Code

Jon Volks
Written By | @webproninja

Computer Science 101, the classic if/else statement which is in every programming language from Javascript to PHP  have. The syntax might be different language to language but the logic is all the same. Today I’d like to dive into the if/else statement and talk about ternary operators (?:). Essentially it’s a short hand way to do an if/else statement inline with the code so don’t have to break out of your current statement.

Lets take a look at a classic example of using if/else statement:

<?php
echo "<p>Is Active: ";
if($active == true) {
echo "Yes";
} else {
echo "No";
}
echo "</p>";
?>

Taking a look at this code, you’ll see that we have seven lines of code to output this one line in html. It’s a lot of space and a lot of code. To help make things more effecient, lets change this to use ternary operators.

<?php
echo "<p>Is Active: ". ($active == true) ? "Yes" : "No" ."</p>";
?>

Seven lines of code is now broken down into one line of code. It’s quick to read and less  code to sort through.

About The Author

Jonathan Volks is currently a Web Programmer at Skidmore College in Upstate New York. He enjoys everything about the Internet; from Search Engine Optimization to Web Programming. His hobbies include landscape photography and hiking the Adirondacks.

Leave a Reply

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