Control Structures

Comparison Operators

// These boolean statements will always evaluate to TRUE or FALSE
// compare equality
42 === 42 //is true
'1' == 1 // is true
'1' === 1 // is false
5 > 5
10 < 15
10 >= 15
10 <= 20
!= is "no equal"
!== is "no identical"
7 != 7 "is false"
!(7 == 7) //is also false, as its says "the opposite of 7==7"
// Used to check the state of the website and control the flow of the code

// Logical Operators
// && is AND

$c = $a && $b;
// || is OR
$c = $a || $b;

echo '<pre>';
var_dump($logic); // logic was array in example.
echo '</pre>';


// ^ is XOR
(true ^ true) is false
(true ^ false) is true
(false ^ false) is false


//Control Structures
<?php

if (10 < 1){

} else if (10 < 4){

} else {

}
?>

$is_logged_in = true;
if ($is_logged_in){
    echo 'logged in';
} else {

}


// Alternative Syntax , this syntax is great is we are printing lots of HTML and we have to exit and enter the php tags alot.

if (condition to check) :
// code to execute if the condition is true
elseif (different condition) :
// different code to execute if the condition is true
else:
// catch all code
<?php if ( $home_page ) : ?>

<header>
    <h1></h1>
    <p></p>
</header>

<?php endif; ?>

// Yoda Conditionals: conditions for checking the equality of variables
Good:
<?php if (10 == $i) {/* do something*/} ?> // always write yoda conditions like this
Bad:
<?php if ($i == 10) {/* do something*/} ?>  // this condition passes even if $i not 10 because in php successful assignment returns true.

// Tenary Operations
$is_logged_in = true;
echo "Welcome' . ($is_logged_in ? " back!" : "!");

//isset function checks if the variable esits
$name = isset($name) ? $name : 'joe';
echo $name;

// alvas condition
$name = null;
$name = $name ?: 'joe';
echo $name


// Switch
// we can use strings and numbers in switch condition and case
$total = 10;
switch( $total ) {
    case 1;
    echo '$total is 1';
    break;
    case 2;
    echo '$total is 2';
    break;
    case 3;
    echo '$total is 3';
    break;
    default:
    echo '$total is more than 3.';
}
// we can also group cases
$total = 10;
switch( $total ) {
    case 1;
    case 2;
    case 3;
    echo '$total is less than 4';
    break;
    default:
    echo '$total is more than 4.';
}

// alternative syntax
$total = 10;
switch( $total ) :
    case 1;
    case 2;
    case 3;
    echo '$total is less than 4';
    break;
    default:
    echo '$total is more than 4.';
endswitch;
Previous
Next