PHP: Shorthand for if and else
Tip by Stefan Trost | Last update on 2023-01-29 | Created on 2012-08-11
Today I want to give you a brief tip along the way, which nevertheless can save a lot of work and can make your code easier to read. It is a abbreviated form for if and else, that not many know.
Let's have a look at an example. We want to output a string and depending on the gender, we want to write "Mr." or "Mrs." The long version of if and else will look something like this:
echo 'We appreciate '; if ($gender == 1) { echo 'Mrs '; } else { echo 'Mr '; } echo $name,' warmly.';
But it is possible to do it shorter. An identical result we get with the short form of if and else:
echo 'We appreciate ',($gender==1?'Mrs ':'Mr '),$name,' warmly';
Especially in this case, the shorthand is more than usefull in clarity and brevity.
To apply the short notation, we must only write the condition infront of a question mark, and then join the two cases separated by a colon behind it. In the example, you can easily retrace the rewriting of a normal if/else statement in the shorthand code.
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile
Related Topics
How to resize Image before Upload in Browser
Tutorial | 13 Comments
jQuery: Send HTML5 Canvas to Server via Ajax
Tutorial | 0 Comments
Send HTML5 Canvas as Image to Server
Tutorial | 0 Comments
Delphi: Event Order of a Form - From OnCreate to OnDestroy
Info | 1 Comment
HTML Form: Redirection depending on Radiobutton or Checkbox State
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
Tips to drink more water
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.