Fri, 17 May 2024
NetArt Media     Pay 2, Get 3!    


PHP If and Else Statements

By: Anton, NetArt Media
Wed, 1 August 2018
PHP If and Else Statements

PHP conditional statements are fantastic, offering coders a large variety of possibilities when it comes to handling variables and data. Whether the data comes from a database or otherwise, using if, else and elseif can make your PHP scripts much more robust.

My last video tutorial used if and else statements and I thought it appropriate to explain them a bit better so your form and MySQL data handling will go a bit more smoothly. There are certain things to remember when using these conditional statements and if not adhered to it could make for a rather frustrating experience. Carried out correctly, however, these statements offer numerous possibilities with positive outcomes.

If Statements - Starting With The Basics



In the code block above I have laid out a basic PHP if statement. This is about as bare bones as you can get. We create a variable that is empty, with the if clause verifying if it is indeed empty and if so, echoing out an appropriate message. The text below is the result in a browser.

The other variable is empty.

If - ElseIf - Else Statements



Now we can take the concept a little bit further and create 3 conditions using if, elseif and else statements. Using 2 variables, each being an integer, we can do some multiplication within the statements to try and find out what the answer is. In this case, we weren't able to and created a message saying as much:

You can't seem to find the correct answer.

More Advanced Conditional Statements




One can get quite advanced with PHP conditional statements, as we see from the code above. Then again, we are only using the if statement in this particular case, where we check the validity of a user's credentials with those in a database and if they are a match, redirect them to a secure area and create a session cookie for them to carry with them during their time within the logged in area.

PHP cookies are something we can get into later on, but I included this example to show you how important PHP conditional statements are. They can literally keep a server safe, in many aspects, along with several other benefits.



Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox