Decision making in PHP

Walden Systems, Geek corner, ad, authenticate, script, geeks corner, json, image, picture, server, file, write, read, close, fread, readfile, fclose, walden, systems, walden systems, php, functions, variable arguments, loops,  for loop, loop, while, do while, break, continue, decision making, ternary, operator, if, then, else
PHP is a popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.

Like most programming languages, PHP also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, we can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions. Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. We need to determine which action to take and which statements to execute if outcome is TRUE or FALSE.

If then else

PHP, like Python, has an if statement for decision making. It consists of a boolean expression that if evaluated to true, will execute a code block. The if statement can also have an else clause which will execute if the boolean expression evaluates to false. The if statement can be daisy chained to multiple if statements.

if(condition1){
    // Code to be executed if condition1 is true
} elseif(condition2){
    // Code to be executed if the condition1 is false and condition2 is true
} else{
    // Code to be executed if both condition1 and condition2 are false
}


The Ternary Operator

The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is represented by the ? symbol and it takes three operands, a condition to check, a result for true, and a result for false. Using the ternary operator the same code could be written in a more compact way. Code written using the ternary operator can be hard to read. However, it provides a great way to write compact if-else statements.




Lines 1 - 8 can be re-written using the ternary operator as seen in line 10.

Switch statements

The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match. The major difference is that the test for the variable happens only once.