Conditionals and Logic in PHP
Conditionals and Logic in PHP
PHP If Statements
PHP if statements evaluate a boolean value or if (TRUE){
expression and execute the provided code block if the
echo "TRUE is always true";
expression evaluates to TRUE .
}
$condition1 = TRUE;
if ($condition1) {
// This code block will execute
}
$condition2 = FALSE;
if ($condition2) {
// This code block will not execute
}
PHP switch statement
PHP switch statements provide a clear syntax for a switch ($letter_grade){
series of comparisons in which a value or expression is
case "A":
compared to many possible matches and code blocks are
executed based on the matching case . echo "Terrific";
In PHP, once a matched case is encountered, the code break;
blocks of all subsequent cases (regardless of match) will
case "B":
be executed until a return , break , or the end of the
statement is reached. This is known as fall through. echo "Good";
break;
case "C":
echo "Fair";
break;
case "D":
echo "Needs Improvement";
break;
case "F":
echo "See me!";
break;
default:
echo "Invalid grade";
}
PHP readline()
The PHP built-in readline() function takes a string with echo "\nWhat's your name?\n";
which to prompt the user. It waits for the user to enter
$name = readline(">> "); // receives user
text into the terminal and returns that value as a string.
input
PHP elseif statements
PHP elseif statements must be paired with an if $fav_fruit = "orange";
statement, but many elseif s can be chained from a
single if .
elseif s provide an additional condition to check (and if ($fav_fruit === "banana"){
corresponding code to execute) if the conditional echo "Enjoy the banana!";
statements of the if block and any preceding elseif s } elseif ($fav_fruit === "apple"){
are not met.
echo "Enjoy the apple!";
} elseif ($fav_fruit === "orange"){
echo "Enjoy the orange!";
} else {
echo "Enjoy the fruit!";
}
// Prints: Enjoy the orange!
echo gettype($is_true);
// Prints: boolean
echo gettype($is_false);
// Prints: boolean
PHP ternary operator
In PHP, the ternary operator allows for a compact syntax // Without ternary
in the case of binary ( if/else ) decisions. It evaluates a
$isClicked = FALSE;
single condition and executes one expression and returns
its value if the condition is met and the second if ($isClicked) {
expression otherwise. $link_color = "purple";
The syntax for the ternary operator looks like the
} else {
following:
condition ? expression1 : expression2 $link_color = "blue";
}
// $link_color = "blue";
// With ternary
$isClicked = FALSE;
$link_color = $isClicked ? "purple" :
"blue";
// $link_color = "blue";
$passingGrades = TRUE;
$extracurriculars = TRUE;
if ($passingGrades && $extracurriculars){
echo "You meet the graduation
requirements.";
}
// Prints: You meet the graduation
requirements.
Print Share