Skip to content

Instantly share code, notes, and snippets.

@recck
Created August 22, 2012 21:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save recck/3429313 to your computer and use it in GitHub Desktop.
Save recck/3429313 to your computer and use it in GitHub Desktop.
Week 2 - Day 3 - Conditional Logic
<?php
/**
* Mathematical Comparison Operators
* x > y, is x greater than y?
* x >= y, is x greater than OR equal to y?
* x < y, is x less than y?
* x <= y, is x less than OR equal to y?
*
* Logical Comparison Operators
* x == y, does x have the same value as y?
* x != y, do x and y have different values?
* x === y, do x and y have the same value and data type?
* x !== y, do x and y have a different value or data type?
* x && y, are x AND y true?
* x || y, is x OR y true?
* x ^ y, is x or y true, and are x and y both not true?
*
*/
// simple if statement
$firstVariable = 8;
if( $firstVariable < 10 ){ // is $firstVariable less than 10?
echo 'True';
}
// what if it isn't?
else {
echo 'False';
}
// multi step if statement
$secondVariable = 10;
if( $secondVariable < 10 ){ // is $secondVariable less than 10?
echo 'Less than 10';
} else
if( $secondVariable == 10 ){ // is $secondVariable equal to 10?
echo 'Equal to 10';
} else {
echo 'It must be greater than 10';
}
// multiple condition if statement
if( $firstVariable < $secondVariable && $secondVariable == 10 ){
// is $firstVariable LESS THAN $secondVariable, and $secondVariable is equal to 10?
echo 'Both conditions are true!';
}
// using a switch statement to compare multiple answers
$thirdVariable = 9;
// the question being asked: what is $thirdVariable, and what to do with that value?
switch( $thirdVariable ){
case 7:
echo 'It must be seven!';
break; // don't forget the break!
case 8:
echo 'It must be eight!';
break;
case 9:
echo 'It must be nine!';
break;
default:
echo 'I have no clue what it is!';
}
// using a switch with combined cases
$fourthVariable = 7;
switch( $fourthVariable ){
case 2:
case 4:
case 6:
case 8:
echo 'The number must be even!';
break;
case 1:
case 3:
case 5:
case 7:
case 9:
echo 'The number has to be odd!';
default:
echo 'Can not compute!';
}
// being able to minimize that switch statement using modulus and an if statement
if( $fourthVariable % 2 == 0 ){
// we ask if the remainder of $fourthVariable divided by 2 is equal to 0
// if it is 0, it is an even number
echo 'The number must be even!';
}else {
// else it is an odd number
echo 'The number must be odd!';
}
?>
@krageon
Copy link

krageon commented Sep 10, 2014

"x ^ y, is x or y true, and are x and y both not true?"

Should probably be

"x ^ y, is x or y true, and are x and y not both true?"

otherwise it reads as a logical paradox (x or y needs to be true, but they also need to both be not true).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment