Short If-Else Structure
Posted by Frank Verhoeven | Filed under PHP
In addition to the enlarged if – else statement that you will use in most cases, there is also a short structure for an if – else statement. This format uses the so-called “ternary operator ‘. The syntax of this shorthand structure is as follows:
$var = [condition] ? [true] : [false];
- Condition = The condition which must be met.
- True = Executed if the condition is met.
- False = Executed if the condition failes.
Thus, the above statement means the same as this enlarged structure:
<?php if (condition) { $var = [true]; } else { $var = [false]; } ?>
Examples
Let’s take a look at some example.
Filled in a name?
<?php $name = isset($_POST['name'])?$_POST['name']:'Unknown'; // If $_POST['name'] exists, we use that for the name, else we use Unknown. ?>
We can also use it to easily echo stuff:
<?php $fruit = 'apple'; echo ('pear' == $fruit)?'pear':'apple'; // Will echo apple ?>
It is even possible to use php-functions inside it:
<?php $input = 'Just a string to be hashed'; $hashMethod = 'sha1'; $hash = ('sha1' == $hashMethod)?sha1($input):md5($input); // $hash will contain an sha1 hash of $input ?>
Conclusion
The short if-else structure is a good way to keep your code organized. However, it is not possible to use such a thing as: ‘elseif’.
I use it all the time to assign values to variables, with just one rule of code, I’m sure my vars have a proper value. Especially when using forms, this is a very useful function of PHP.
October 4th, 2008 at 5:50 am
Nice explaination. My problem with this syntax is that there aren’t many people out there who know what this means. I always worry about readability. Though I do love single-line solutions…
March 3rd, 2009 at 10:23 am
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
April 16th, 2009 at 5:26 am
thanks for the good article.
explanation was very clear on short if-else statement.
September 5th, 2009 at 3:20 pm
Answer this,Created a flowchart and program that will accept a number from (1-7) and display the equivalent day of the work display “Error” for other numbers,use if-else and switch statement…
September 5th, 2009 at 3:23 pm
thankz hope you can answer this….
November 25th, 2009 at 3:55 pm
Good point Alexwebmaster there is some horrendous code out there which would only be worse had they used this format. It is useful though
Nothing you have not covered but another summary: Short PHP statements