PHP If Statements – Making Decisions PHP Tutorial

PHP If Statements can help you make decisions in code. I figured before I jump into the shopping cart, I should show you how to use if else statements which are common among many programming languages PHP included. They include if, else, and else if. I will share examples for each case and finally touch on switch statements and Arrays in this php tutorial.
php if statements

PHP if Statements

#Conditional statements are used to make decisions in programs
#Here is the skeleton:
if (condition){
//do something
//do something else
#Let me drive this point home a little easier!
if (your electric bill is due){
//go pay your bill pal
//don’t worry about it, just enjoy the light

#Note that you can have an if statement without an else part!
$age = 20;
if ($age > 18){
echo ‘You are old enough to move out now’;
#In these php if statements, since $age is 20 (greater than 18),
#the condition will be true hence echoing ‘You are old enough
#to move out now’. If age was less than 18, nothing would happen
#so, you just keep living in your parents’ garage!

#Now let us consider a scenario where you have to choose from
#more than two things:

$name = ‘Walter’;
$sister = ‘Kim’;
if($name == ‘Kim’){
echo ‘My name is Kim Kardasian’;
}elseif($name == ‘Walter’){
echo ‘My name is Walter Reeds’;
echo ‘I am not either of those!’;

#As an exercise, try out student grades: 90-100: give an A
#80-90: give a B and so forth [give an F a 60!]

#Other ways of making decisions with logical operators:
$age = 20;
$country = ‘USA’;
if($age >= 18 && $country == ‘USA’){
echo ‘You can get a drivers license now’;
echo ‘Consult your respective country for this’;
#Note: in order for the above condition to work,
#both conditions MUST be true. You can use an OR (||)
#operator to check conditions: In that case,
#short-circuiting takes place::::::::::::::
#if the first part is true, the second part is not checked.
#if the first part is false, the second part is checked.

Alternative: The Switch Statements.

Assuming you have 20 items in a list and you just want to pick one of them. Consider a menu item at your favorite restaurant(I hate looking through those entrees, that is why I almost eat the same thing every time I go there). Now think about writing if statements to check for all of them. Ouch, that will be tedious – the good thing is this: you do not have to do that, thanks to the switch statements. Let us take a look at one now!

#Let us see how useful a switch statement is:
#Grade the student scores – assume a teacher’s role!
$score = 90; //you could prompt users to enter score here.
case 60:
echo ‘You could have done better than that!’;
case 70:
echo ‘You have potential to improve!’;
case 80:
echo ‘Good but not the best. Try a little harder’;
case 90:
echo ‘Very very good job son, now move on’;
case 100:
echo ‘Excellent work! Pat yourself on your shoulder’;
echo ‘You might have been in the wrong class pal’;
#Here is a short explanation for a switch statement.
#You might have noticed ‘break’ and ‘default’ keywords
#break: this tells PHP that it is the end of the switch
#and so execution should now exit and continue with the rest
#of the page.
#default: this is the last option – just in case none of the
#cases match the correct value. That is it!

Finally in this php if statements tutorial, let us give Arrays a good look:

Using Arrays in PHP with if statements

When you want to store multiple values in one variable, you use …you guessed it, an array! Consider these two types of basic arrays: Numeric and Associative arrays:

#Numeric Arrays:
#if you want to list things you can do this:
$item_1 = ‘Kenya’;
$item_2 = ‘USA’;
$item_3 = ‘UK’;
$item_4 = ‘Brazil’;
#Or we can actually put all those in an array like this:
$countries[0] = ‘Kenya’;
$countries[1] = ‘USA’;
$countries[2] = ‘UK’;
$countries[3] = ‘Brazil’;
$countries[4] = ‘Canada’; #don’t forget Canada, right?
#Let us now print some of the values in our array!
echo countries[0].” and “.countries[1].” and “.countries[4];

#All arrays have a key and a value and all keys start with a zero
#in numeric arrays as shown above. So, you simply access the value
#by using the key [digit].

#Associative Arrays:
#You might be thinking: what if I wanted to use a string
#as the key in your array? Yeah, good point and there is no
#need to beat around the bush here, we call that Associative arrays
$countries[‘kenya’] = ‘Found in Africa’;
$countries[‘usa’] = ‘Located in North America’;
$countries[‘brazil’] = ‘In South America’;
$countries[‘china’] = ‘Asia anyone?’;

#We can echo them like numeric arrays! Sweet.

echo $countries[‘usa’].” and “. countries[‘kenya’].” whatever here”;


Putting Arrays To Use:
The biggest question running through your mind might be: when do we use these Arrays? Let us take a quick look at an example here and let you go out to the world as an explorer for more knowledge!

#Let us create a brand new array here and add some stuff to it:
$students = array(‘Alexie’, ‘Jimmy’, ‘Kim’, ‘Grace’, ‘Peter’);
#you can create an array that way! Easy right?
#Now let us use our array to do crazy cool stuff!
if(in_array(‘Jimmy’, $students)){ #hay in a haystack!
echo ‘Jimmy is one of the students’; #true
echo ‘Jimmy is not one of the students. <br />’;
echo ‘We only have the following names:<br />’;
foreach($students as $student){
echo $student. ‘<br />’;

#So what did we just do there? In short, we created an array,
#using the array() function,
#added some values to it and then use one of the array functions
#or methods (in_array) to check if a certain value exists in the
#array. If the value exists, we simply print it out, otherwise,
#we say that it doesn’t exist and print all the values using
#a foreach construct.

#Other things you can do with arrays:
echo count($students); #what is your guess?
echo key($students); #get the index element of current array
echo rsort($students); #sort in reverse

echo ‘Visit PHP documentation for more array functions!’;

PHP if statements Summary:
Thank you for reading through this long post. I really wished it was shorter but hey, I could have shortened it and miss some important stuff. Either way, I think I have covered some significant ground here as far as if else statements, switch statements and finally arrays(watch out for hash tables, they mean the same thing in the PHP world). Because I did not exhaust everything here, I want to leave you with a link to the PHP documentation where it all started!

PHP Documentations

Thanks again and if you have any questions or have spotted any errors in my post, let me know. Any opinion(negative or positive) is very important and much appreciated. I have said this before but I think my next post will include building a simple shopping cart! See you soon and get coding!

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

4 Comments on “PHP If Statements – Making Decisions PHP Tutorial

  1. brunoais Reply

    January 19, 2013 at 12:12

    Nice stuff. really complete and straight forward for a crash introduction to php. With this and the previous post, I believe you have already given the main juice behind how to program in php. I sure hope you give the remaining ( functions) to the shopping cart you said you are working on.

    Now for the problems…

    You should have given just a small, simple example of what happens if you don’t use break in the switch. With that warning in place, you’ll prevent people from forgetting it and also they will not have the idea of using break every time hammered into their heads (using it or not is case sensitive (pun intended). At least, understanding that helped me a lot when I started programming.

    “if(in_array(‘Jimmy’, $students){ #hay in a haystack!”
    Syntax error. There’s a “)” missing (I also make mistakes like those 😉 )

    To prevent misconceptions, I think you should call in_array() explicitly as a function and not mention methods.

    foreach is a language constructor, just like if, switch, etc… Not a function.

    • joylaxpower Reply

      January 19, 2013 at 6:23

      Again, I cannot believe I missed that error. Thank you so much for stopping by and taking your precious time to read through my code and point out really important points. I truly appreciate!

      • brunoais Reply

        January 19, 2013 at 6:58

        All for the sake of completeness and for the correctness for the one’s that follow us in the steps of learning a programming language ;).

        • joylaxpower Reply

          January 19, 2013 at 7:04

          I would like to talk to you further! You intrigue me and I have a question that I figured could be perfectly fit for you! Are you on Twitter? Or Google+? Let us, please, connect!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.