PHP MySQL tutorial

PHP if elseif else statements

Very often, while writing the code, some decisions are required to perform certain actions. In PHP, you can use following decision making statements for the same.

  • if statement
  • if else statement
  • if elseif else statement
  • switch statement

The if statement

It executes the code for specific one condition.

Syntax

if (condition) {

// Block of code; // Executed only if condition is true

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	if ($KH_CurrentDay != "sun")
	  echo "Today is not a holiday";
?>

Download the code Run the code

The if…else statement

It executes some set of statements if condition is true. Otherwise, execute another set of code if condition is false.

Syntax

if  (condition) {

Block of code; // Executes only if condition is true

}  else {

Block of code; // Executes only if condition is false

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	else
	  echo "Today is a working day";
?>

Download the code Run the code

The if elseif else statement

It executes different set of statements depending on the conditions.

Syntax

if (condition) {

Block of code; // Executes only if condition is true

} elseif (condition) {

Block of code; // Executes only if above condition is false and this condition is true

} else {

Block of code; // Executes only if all above condition are false

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	elseif ($KH_CurrentDay == "sat")
	  echo "Today is a half working day";
	else
	  echo "Today is a working day";
?>

Download the code Run the code

We will discuss the Switch statement in the next chapter.

<<< PHP OperatorsPHP Switch Statement >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .