Let's Get Logical!
In most programming languages the if statement is the main logic test. The example below will check the value of $num to see it its value is equal to 5. We use an echo statement here to output a message. Echo and other functions will be covered later in the lessons.
Code Box
if ( $num == 5 ) {
// Anything between the opening { and the closing } is what
// happens when $num is 5.
echo "The variable was set to 5";
};
// Anything between the opening { and the closing } is what
// happens when $num is 5.
echo "The variable was set to 5";
};
If we needed to do something else if the value wasn't 5 then here's what we do. This is typically called an if-else statement.
Code Box
if ( $num == 5 ) {
echo "The variable was set to 5";
} else {
echo "The variable was NOT set to 5";
};
echo "The variable was set to 5";
} else {
echo "The variable was NOT set to 5";
};
So far we have checked if a number is of a certain value. We can also check the true / false value of functions or boolean variables.
Code Box
if ( call_home() ) {
echo "Call home was success";
};
echo "Call home was success";
};
In the above example we are running a function (learn later tutorial) and only if the function runs successfully will the output be displayed.
Code Box
if ( $learner ) {
echo "Learner is set";
};
echo "Learner is set";
};
In the code above we are basically checking if the variables learner has a value other than "false" or 0. So for any other value stored in $learner then the output is produced.
A few more examples...
Code Box
if ( $num >= 5 ) {
// This time we are checking whether $num contains a value of 5 or above.
};
// This time we are checking whether $num contains a value of 5 or above.
};
Code Box
if ( $num < 5 ) {
// This time we are checking whether $num is less than 5.
};
// This time we are checking whether $num is less than 5.
};
Code Box
if ( $num != 5 ) {
// This time we are checking to make sure that $num ISNT equal to 5.
};
// This time we are checking to make sure that $num ISNT equal to 5.
};
Code Box
if ( $num = call_home() ) {
// This kind of logical statement can be confusing.
// But you can come back to look at this
// once you have fully learnt about functions.
// Basically this is checking whether the function
// named "call_home" is returning a value other than 0 or false.
// At the same time we are also storing the value returned
// by the function into the variable $num.
};
// This kind of logical statement can be confusing.
// But you can come back to look at this
// once you have fully learnt about functions.
// Basically this is checking whether the function
// named "call_home" is returning a value other than 0 or false.
// At the same time we are also storing the value returned
// by the function into the variable $num.
};
discuss this topic to forum
