SEARCH
Newsletter
Subscribe to get design
tips, latest trends, free
stuff and more.
It doesn't look like an e-mail address

hosting

  Web Programming PHP Using PHP \'if\' Statements

Using PHP 'if' Statements

Alex PHP Jan 09, 2007

Using PHP 'if' StatementsThis isn't a step by step tutorial but more of an explanation on how 'if' statements work.

Here is the basic syntax of an 'if' statement. Remember that the 'else' statement is not necessary.

<?

if (something == something else) {
'then' statement
} else {
'else' statement
}

?>

Usually, 'if' statements are used to compare variables. All variables in php start with a "$" sign. The 'if' statement looks at the variable you specify, and checks to see whether it is indeed the 'something else' you specify.

if ($name == "alex")

The 'then' statement will only run when the 'if' statement is true:

if ($name == "alex") {
print "Hello, Alex";
}

Now, when $name == "alex", the text "Hello, Alex" will show on the page. You could leave the script like this and it would just end there. But, if you wanted to display something else if $name wasn't "alex", you would add an 'else' statement:

<?

if ($name == "alex") {
print "Hello, Alex";
} else {
print "Hello, person who is not named Alex.";
}

?>

Now that we added the 'else' statement to our script, if $name isn't "alex", the browser will output the text "Hello, person who is not named Alex." Above is the entire script. You can use 'if' statements to do much more with PHP, but this is just a very simple introduction to them.

   
subscribe to newsletter