The PHP if statement

Category: PHP

We think you might be interested in this job:

The PHP if statement | C.S. Rhymes C.S. Rhymes HomeBooksNigel's Intranet AdventureHow NOT to make a WebsiteHow NOT to use a SmartphoneMy WorkThemesProjectsSitesStoriesSponsorsAboutBlogSponsorThe PHP if statementPHP FundamentalsPublished: May 6, 2021 by C.S. RhymesThis is the first of a series of posts I will write that go back to basics and introduce the fundamentals of PHP. The purpose of an if statement is to have a condition, or test, and if that passes then run the code within that section.

If you have an IDE or a good text editor you can normally click on the opening bracket and it will highlight the opening and closing bracket so you can see where each section starts and ends.$myVar=true;if($myVar===true){echo"It is true";}else{echo"It is false";}With ColonsSometimes it’s easier not to use curly brackets and use colons instead.

But this may not be the case, it could be null or it could be a string, an integer, etc.If we want to make sure that $myVar is actually false before echoing out “It is false” then we can use an else if to add another condition check.$myVar=true;if($myVar===true){echo"It is true";}elseif($myVar===false){echo"It is false";}You can also add a further else onto the end to catch the cases that don’t fit into the if or else if conditionals.$myVar=true;if($myVar===true){echo"It is true";}elseif($myVar===false){echo"It is false";}else{echo"It is neither true or false";}You can add multiple elseif statements if you want to, but then you may want to use an alternative, such as switch statement, instead.ElseIf or Else IfWhen using curly brackets you can use elseif or else if and they both do the same thing.

If it isn’t null, then the condition is used, otherwise it will use the second item (after the ??).$myVar='This is a string';echo$myVar??"It is null";// This is a string$myVar=null;echo$myVar??"It is null";// It is null// The equivalent of this ternary statementechoisset($myVar)?$myVar:"It is null";In summaryHopefully this will give you a bit more background into the PHP if statement and what is possible.

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners