Saturday, August 16, 2008

PHP if statement

Control structures are the fundamental elements of PHP (and any other programming language). These structures allows you to controll the program / script flow. In PHP there are more control structures and we can split them into 2 categories.

  • Conditional statements
  • Iteration statements
In this description I will focus only on the if statement which is maybe the most important conditional statement.
You can use the if statement if you want to execute a set of code when a condition is true. It is very similar as in C. The syntax is the following:
if (condition) code to execute in case the condition is true;
Let's see a real example.

Code:


if ($userName == 'Peter') echo 'Hello Peter!';
 

PHP F1



Notice that we used == in the condition and not =. This means that we want to check the equality og the left and right values and we don't want to assign a new value to the variable.

In this example there was only a one line statement to be executed if the condition is true. Of course you can use a complete code block. In this case you have to put all relevant code in a code block separated by { and } as follows:



Code:


if ($userName == 'Peter') {
echo 'Hello Peter!';
echo 'Nice to see you again!';
}
 

PHP F1



 



In the previous step you have learnd the basic syntax of the if conditional statement. Now it's time to extend your knowledge a little bit. In PHP there are to check operators you can use as condition. In our previous example we used the == . However you can use the === as well. Yes, it is not a mis-spelling.

The difference between the 2 versions is the following:




  • X == Y : True if X is equal to Y


  • X === Y : True if X is equal to Y and X is the same type as Y.


So let's see a real life example:

Code:


$X = 1;
$Y = true;

if ($X == $Y) {
echo "First test OK!";
}

if ($X === $Y) {
echo "Second test OK!";
}

PHP F1



In this example only the first test will pass as $X is an integer variable and $Y is a boolean. As the boolean true can be intrpreted as number value 1 so the first test will pass but as they have different types the second test will fail.

No comments: