How to use the if-else statement in PHP?

Member

by dana , in category: PHP General , 2 years ago

How to use the if-else statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , 2 years ago

@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.

Member

by larissa , a year ago

@dana 

Here's an example using the if-else statement to check if a number is positive, negative, or zero:

1
2
3
4
5
6
7
8
9
$num = -5;

if ($num > 0) {
  echo "$num is positive";
} elseif ($num < 0) {
  echo "$num is negative";
} else {
  echo "$num is zero";
}


In this example, the if statement checks if the number is greater than 0. If it is, the code inside the if block will be executed and "num is positive" will be printed. If the number is less than 0, the elseif statement will be evaluated and "num is negative" will be printed. If neither of these conditions are true, the else block will be executed and "num is zero" will be printed.