RSS

Basic IF Loop

Fri, Jan 15, 2010

PHP & MySql

Note: everything put between … and … is NOT an actual code but are just ‘comments’ that indicate what should be put in there.

Loops are very useful and used a lot in PHP. They’re used to check conditions and act based on whether the condition checked was true or false. A basic loop to do this is the If loop.As mentioned above a loop consists of a condition and an ‘act’ (what if the condition is true? What if the condition is false?). A basic if loop looks like this:

If( ... condtion ... ) {
  ...act when true ...
} else {
  ... act when false ...
}

You can see the condition is put between the brackets, and the act is between { and }. The ‘act’ of the else part of the loop runs when the condition was false. When you don’t want the system to do anything if the condition was false, then you can just leave out the else part, so you’d get:

If( ... condtion ... ) {
  ... act when true ...
}

Ok so let’s actually use this. Take for example that you sell products on your website, and members have their own balance which represents the money they own. Now when they are going to use this balance to buy a product, you will need to check whether his balance is high enough to buy that product. Therefore an if-loop is needed! A simplified example :

<?php

$price = 10.00;
$balance = 11.95;

If ( $price > $balance ) {

echo "Sorry, your balance is not high enough to buy this product.";
exit(); //cancel the process

}else{

echo "Product bought!";
$balance = $balance-$price; //set the new balance

}

?>

In this case $price contains the price of the product and $balance the amount of money the user
owns on his account. The if loop now checks the condition $price > $balance, which means: $price is
greater than $balance. When this condition is true (when the price is higher than the user’s balance),
the user can not afford to buy the product and the error message is shown – the process is canceled.
However when the price is not higher than the balance (so the user’s balance is high enough to buy
the product) the product is bought and the new balance is set (the price is reducted from the
balance).
So, In this case the above script would return:

Product bought!

And after the loop, the variable $price would contain the value: 1.95
Here we used the operator > to check whether a value was greater than another variable, but of
course there are more operators to use in a loop. Here’s a list of them and their meanings:

== Is equal to
!= Is not equal to
= Set equal to
> Greater than
=> Equal to or greater than
< Smaller than
<= Equal to or smaller than

Alert: Don’t ever use the = operator to CHECK a condition, it’s used to SET variables equal to values.

Admin.