@dana
The if-else
statement in PHP is used to conditionally execute a block of code. Here is the basic syntax for using the if-else
statement in PHP:
1 2 3 4 5 |
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false } |
Here, condition
is a boolean expression that evaluates to either true
or false
. If the condition is true
, the code inside the if
block will be executed. If the condition is false
, the code inside the else
block will be executed.
Here's an example that uses the if-else
statement to check if a number is even or odd:
1 2 3 4 5 6 7 |
$num = 7; if ($num % 2 == 0) { echo "$num is even"; } else { echo "$num is odd"; } |
In this example, the %
operator is used to determine the remainder of dividing $num
by 2
. If the remainder is 0
, then $num
is even, otherwise it is odd. The if-else
statement is used to print out the appropriate message depending on whether $num
is even or odd.