If statements

Saturday 28th of November 2009 in PHP

An introduction to if statements and else statements

When your interacting with php from time to time you may want to show something else depending on a condition this is very simple to do using if and if else statements.

The syntax for an if statement goes like this:


<?php

if (condition) { 

//do something

}

?>

then this can include an else statement


<?php

if (condition) {

//do something

} else {

//do something else

}

?>

This can be expanded further using an ifelse statement:

 

<?php

if (condition1) {

//do something

} elseif (condition2) {

//do something else

} else {

// do something diffrent

}

?>

In the first example if (condition) { means in condition is true then do what ever is between the brackets { } in this case it was only a comment.

Then next example was in first condition is not true then do the else again this was only a comment.

The third example was if condition1 is not true then do condition 2 but if that's not true either then do the else.

Using if statement can be really useful for example you could have a different welcome message depending on what someone fills in on a form.

Lets make a simple form:


<form method="post" action="<?php $_SERVER['PHP_SELF'];?>">

Name:<input type="text" name="name"/>

<input type="submit" name="submit" value="submit" />

</form>

This form asks for a name and has a submit button to send to form. The form will reload the page once it has being sent using the php global variable


<?php

$_SERVER['PHP_SELF']

?>

Now we will use an if statement to see if the form has being submitted:


<?php

if(isset($_POST['submit'])){

?>

If the form has been submitted we then get the name from the form using


<?php

$name = $_POST['name'];

?>

We now check to see what the name is and show a message


<?php 

if ($name == 'dave'){ // if name is equal to dave print message

echo "<p>Dave is your name</p>";

} elseif ($name == 'tony') { if name is equal to tony print message

echo "<p>Tony is your name</p>";

} else { if not equal to dave or tony then print their name

echo "<p>your name is $name</p>";

}

?>

Now we close the bracket for if the form has being submitted with a closing bracket '}'

Here's the full script:


<?php

if(isset($_POST['submit'])){

$name = $_POST['name'];

if ($name == 'dave'){ // if name is equal to dave print message

echo "<p>Dave is your name</p>";

} elseif ($name == 'tony') { if name is equal to tony print message

echo "<p>Tony is your name</p>";

} else { if not equal to dave or tony then print their name

echo "<p>your name is $name</p>";

}

}

?>

<form method="post" action="<?php $_SERVER['PHP_SELF'];?>">

Name:<input type="text" name="name"/>

<input type="submit" name="submit" value="submit" />

</form>

This is a very basic example of using if statements to give you a simple example of how to use them.