It's often the case that you will need to check whether 2 or more things equate to true/false. Using the code below we are ensuring that both conditions are true for the code to execute. The output is only displayed when variables a and b set.
Code Box
if ( $a && $b ) {
echo ( "This is some output that would happen when both are true" );
};
echo ( "This is some output that would happen when both are true" );
};
Of course we can do more complex examples. Using brackets to seperate each part can help you to understand it!
Code Box
if ( ($a > 10) && ($b < 12) && ($c >= 2) ){
// Put some code here to do when the conditions above are true.
};
// Put some code here to do when the conditions above are true.
};
With PHP we can also use logic statements within other logic statements.
Code Box
if ( $con == 1 ) {
$con = $con + $num; // You can ignore this line if you like //
if ( $con == 1 ) {
echo ( "$num is set to 0 or not set at all" );
};
};
$con = $con + $num; // You can ignore this line if you like //
if ( $con == 1 ) {
echo ( "$num is set to 0 or not set at all" );
};
};
A second evaluation....
We have learnt some basic if else logic. We can also use the ' elseif ' keyword to carry out another action should the second criteria evaluate to true.
Code Box
if ( $number > 3 ) {
echo ( "The variable is greater than 3" );
} elseif ( $number < 3 ) {
echo ( "The variable is less than 3" );
} else {
echo( "The variable is equal to 3, because its not greater than or less than 3" );
};
echo ( "The variable is greater than 3" );
} elseif ( $number < 3 ) {
echo ( "The variable is less than 3" );
} else {
echo( "The variable is equal to 3, because its not greater than or less than 3" );
};
Shorthand Syntax!
It's possible to use the same kind of if else logic using a lot shorter code. This is called shorthand code and can look very complicated if you begin to use it a lot. For that reason programmers tend to prefer the longer version. As well as looking neater the longer version allows for more flexibility. The short version really only is used for choosing between 2 different things to output or return. Let's see an example.
Code Box
$data = ( $con == 1 ? "Connected" : "Not Connected" );
The block of code above looks a little complicated unless you know the rules behind it. Basically we are checking whether the variable called con contains the numerical value of 1. If it does the string "Connected" is stored into the variable called data, otherwise the string "Not Connected" is stored into $data.
Below is the same piece of code in RULE form.
Code Box
= ( Condition ? Value_True : Value_False )
It's starting to get a little more complex now so if you are unsure about anything covered in this topic post a comment below, thanks.
discuss this topic to forum
