PHP if condition with example

An if condition in PHP is used to execute code when a certain condition is met. The syntax for an if condition is as follows:


if (condition) {

  // Code to be executed if condition is true

}


The condition can be any expression that evaluates to a Boolean value. For example, the following code will print "The number is even" if the variable $number is even:


$number = 10;


if ($number % 2 == 0) {

  echo "The number is even";

}

If the condition is not met, the code inside the if block will not be executed. For example, the following code will not print anything:


$number = 11;

if ($number % 2 == 0) {

  echo "The number is even";

}

You can also use an else block to execute code when the condition is not met. The syntax for an else block is as follows:


if (condition) {

  // Code to be executed if condition is true

} else {

  // Code to be executed if condition is false

}


For example, the following code will print "The number is odd" if the variable $number is odd:


$number = 11;

if ($number % 2 == 0) {

  echo "The number is even";

} else {

  echo "The number is odd";

}

You can also use an elseif block to execute code when a specific condition is met, but the original condition was not met. The syntax for an elseif block is as follows:



if (condition) {

  // Code to be executed if condition is true

} elseif (condition) {

  // Code to be executed if condition is true, but the original condition was not met

} else {

  // Code to be executed if neither condition is met

}


For example, the following code will print "The number is even" if the variable $number is even, or "The number is divisible by 3" if the variable $number is divisible by 3, but not even:


$number = 12;

if ($number % 2 == 0) {

  echo "The number is even";

} elseif ($number % 3 == 0) {

  echo "The number is divisible by 3";

} else {

  echo "The number is neither even nor divisible by 3";

}


If statements can be nested inside each other to create more complex conditional logic. For example, the following code will print "The number is even and greater than 10" if the variable $number is even and greater than 10:


$number = 12;

if ($number % 2 == 0) {

  if ($number > 10) {

    echo "The number is even and greater than 10";

  }

}


I hope this helps!

No comments:

Post a Comment