Jump to content

If else vs Shorthand If


Recommended Posts

Nice be with you everyone! What is the main difference between If else and Shorthand If? Example:

 If ($gender == 'male') echo 'Hi Sir!'; else echo 'Hi Mam!'; and ($gender == 'male') ? echo 'Hi Sir!' : echo 'Hi Mam!';

Thank you in advance!

Link to comment
Share on other sites

In your example? Nothing. But notice that the second can be clarified a little like this:

echo ($gender == 'male') ? 'Hi Sir!' : 'Hi Mam!';

That is, someone else reading the code (including you 2 weeks from now) can look at my example and know immediately that the statement will echo something. I also generally recommend that developers NOT write if-blocks without {braces}. It seems like it's not a big deal, but it can become a problem if you or someone else needs to add statements later, and you don't remember to add the braces. It happens to people all the time.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...