Multiple Conditions: && and ||

A Boolean expression can test more than one condition using && for AND, || for OR:

if (expression1 || expression2) statement;
The statement is executed if expression1, expression2, or both are true.

if (expression1> && expression2) statement;
The statement is executed if both expression1 and expression2 are true.

Note: Each side of the && or || must be a complete Boolean expression. The statement
if (x < 5 || > 100)... is not allowed: it must be written if (x < 5 || x > 100)...

Example: A restaurant gives a 50% discount to children ages 6 and under and to seniors 65 or older.

The important thing about examples like this is that the general rule uses and, ie children AND seniors, but the code is evaluating just one condition. The person will get a discount if he is a child OR a senior.

Put this code in a test file and add values for age and price to the URL: TEST PAGE

<?php
if($age <= 6 || $age > 65) {
  $price=$price/2;
  echo 'The discounted price is $'.number_format($price, 2,'.',',').'<BR>';
} //true
else {
  echo 'The price is $'.number_format($price, 2, '.', ',').'<BR>';
} //false
?> 
Try different values in the URL such as discount.php?price=25&age=6 or ?age=60&price=23.89

It is very important to test each condition. You should test an age under 6, 6, 65, and an age over 65. You should try a few different prices as well.

Look at the manual for information about number_format which allowed us to print the amount with 2 decimal places.


INDEX, Boolean Values, if/else, Summary, Compound Conditions: AND && and OR ||, SWitch
Next lesson: Important InformationMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Compound Conditions: AND && and OR ||