Most experienced programmers already know this, but this is a quick trick that will save you a few lines of code if you have a really simple if-statement to display one thing or another. This works with both PHP and Perl and will help you cut down some coding time. For this post we will show PHP. Lets begin:
<?php $id=$_GET['id']; if($id==1) echo "Welcome Guest, please register to use this page."; else echo "Welcome back!"; ?>
This is fairly simple to understand, and most people have statements like this through out any webpage. There is a trick that makes the coding much shorter. I have no idea what it is called, so we will call it an inline-if-statement. It utilizes the question mark (?) and colon (:) to execute simple if statements. Lets rewrite the above code:
<?php $id=$_GET['id']; echo "Welcome ".($id==1?"Guest, please register to use this page.":"back!"); ?>
We summed up those 4 lines into one line of code. I typically encase the statement in parenthesis, but you don’t need to. The first part is the if-statement. If($id==1) becomes $id==1?. Then if $id was equal to 1, it would append "Guest, please register to use this page." to "Welcome ". else is now just a colon : and separates the two values.
Why is this useful? Well its quicker code. 4 lines of code is now compressed to a single line.
Why would you not use it? Well if you need to do other things within the if-statement. This is strictly for displaying data. If you need to change variable values, or call a function, then you would definitely not use this. You would also not use this if you have “else if” statements. This is strictly, if-else.
Hope this helps!
haha, out of all the php i know, i didnt know you could do
” ($id==1?”Guest, “… learned a thing thanks again
Yup, I definitely didn’t learn it until I saw it in other people’s code and was a little freaked by it. Made it a whole lot simpler tho.
I would assume that with the reduction in lines and characters the abbreviated version would run faster, albeit small. Is this true?
Yeah, it does run faster. Doing just a simple timer using microtime() on my computer, it took .0002 seconds to echo a line. It took about .0007 – .0009 seconds to do an inline if statement. To do a full if/else statement, it was about .0001 – .0015 seconds. But hey, I have a slow laptop.
I think a lot depends on the complexity of the if statement as well. I have one that has 3-4 conditions and sub-if statements in the same line of text. The only thing I don’t like about them is that it makes your code confusing, and it may take a minute to remember exactly what that line was supposed to be doing, especially in cases where you have 3-4 conditions.