You Are Here: Home »Tutorials»PHP & MySQL »   If Else Statements

If And Else Statements

Introduction

If and else statemets are very simple, but also very useful when you want to show or do something on your page that relies on certain conditions.

The Syntax

The basic syntax for an if statement:

<?php
if(== b) {
# do something
}
?>

For example, lets say you only wanted to show a certain section of content to somebody when they requested a particular page on your site, you could use the following:

<?php
if($_SERVER['SCRIPT_NAME'] == '/somepage.php') {
           
# show the content you want
}
?>

The basic syntax for an if statement, also using the "else" option, you don't have to just echo content, you can run a function or do whatever else you like based on the condition(s).

<?php
if(== b) {
   
# do something
}
else {
   
# do something else
}
?>

An example of how you would use that in lets say, a login script:

<?php

$input 
== 'thingy';
$password == 'banana';

if(
$password == $input) {
   echo 
"Password correct, you may enter\n";
}
else {
   echo 
"Sorry, wrong password\n";
}

?>

So if we set the password that people enter as a variable called "$input" the if statement will check if it's the same as the real password "$password" and if so echo the text "Password correct, you may enter" but if it's not the same, like in this case they will get the result of the else statement.

Operators

There's really not alot more to it than that, of course there's other operators you can use rather than if this == that (equals), some examples being:

  • == is equal to
  • === is identical to
  • != is not equal to
  • < is less than
  • > is greater than
  • <= is less than or equal to
  • >= is greater than or equal to

The best thing to do with if statements and conditionals is to play about with them and just try different things, and i'm sure you'll be able to think of many ways to make use of them in your pages.