As we have already learnt about data types, we will now study about logical expressions and also about switch. Logical expressions are basically if else statements. You might have given orders to somebody like if jam is available then apply that on bread else if butter is available, then apply that else don’t apply anything. We can also write such commands in PHP. It is a very important and useful topic. So let us learn about it!
Explanation of if conditionals
The if conditional is one of the most important features of many languages, PHP included. It allows you to execute a code when there is a condition. If code in PHP is similar to that of C. Here is how it is written:
The above code can be written in many ways. For now, see where there is written the word – “expression”. Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest and the most accurate definition of an expression is – “anything that has a value”. So, by writing an expression as a condition in if conditionals, PHP will try to evaluate it. The result of the if statements comes as true or false (which are known as booleans). If the expression evaluates to true, PHP will execute the statements, and if it evaluates to false, it will ignore them. More information about what values evaluate to false can be found here. Also note that they do not require semicolons (“;”) except after the statements.
The switch statement is similar to a series of if statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. Please see a sample code here for more explanation. The online demo for the same is here.
I hope that you enjoyed the post 🙂 . Please do ask your query if you have any problems in the comments section. We will discuss about loops in the next post.
(Image Credits: KLJ)