PHP if

Sometimes you need to do different things depending on the value of a variable (or something else). For example, add this to the PHP page you already have (firstphppage.php) to replace the existing line which ECHOes the total:

if ($firstvalue==$secondvalue) {
    echo "<p>the values are the same</p>";
}            
        

The IF statement compares the two values and if they are the same something happens. The condition is held inside normal brackets and the action is inside curly brackets (or braces). Note the use of the == operator. This is used because = means to "set something equal to something else". Double equals means to compare things.

Upload the page and try it. Nothing should happen because the condition failed. Change the values for the variables in the code to make them the same. Upload and try again.

Greater than and less than

To check if a value is less than another:

if ($firstvalue<5) {
        

Greater than uses the > symbol. You can also check if something is less than or equal to:

if ($firstvalue<=5) {
        

Greater than or equal to works the same way.

Multiple conditions

You can include more than one test in an IF condition. For example, this checks if either of two things is true (OR):

if ($firstvalue>5 || $secondvalue>3) {
        

This checks if both of the two checks are true (AND):

if ($firstvalue>5 && $secondvalue>3) {            
        

If the values were 8 and 2 the first IF would result in a yes (TRUE) because 8 is more than 5. The second IF statement would result in no (or FALSE) because although 8 is more than 5 2 is not more than 3.

NOT

You can also use negative conditions such as this one:

if ($firstvalue!=5) {
        

This means "is not equal to".

submit to reddit Delicious Tweet