Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. if / elseif / else

if / elseif / else

Conditional branching is a mechanism that switches which code to execute based on the result of a specified condition expression. In『PHP』,『if』,『elseif』, and『else』can be combined to write multiple branches.

Syntax

// if only
if (condition) {
	// process executed when condition is true
}

// if...else
if (condition) {
	// process executed when condition is true
} else {
	// process executed when condition is false
}

// if...elseif...else
if (condition1) {
	// process executed when condition1 is true
} elseif (condition2) {
	// process executed when condition1 is false and condition2 is true
} else {
	// process executed when no condition is true
}

Each Part of the Syntax

SyntaxDescription
if (condition)Evaluates the condition. If the result is『true』, the immediately following『{ }』block is executed.
elseif (condition)When the preceding condition was『false』, evaluates a new condition. Multiple elseif clauses can be chained.
elseOptional. The block executed when all preceding conditions are『false』.

Common Comparison Operators

OperatorMeaningDescription
===Identical (strict)Returns『true』when both value and type match.
!==Not identical (strict)Returns『true』when value or type differs.
==Equal (loose)Compares values after type coercion. To avoid unintended behavior, use『===』normally.
!=Not equal (loose)Returns『true』when values differ after type coercion.
>Greater thanReturns『true』when the left operand is greater than the right.
<Less thanReturns『true』when the left operand is less than the right.
>=Greater than or equalReturns『true』when the left operand is greater than or equal to the right.
<=Less than or equalReturns『true』when the left operand is less than or equal to the right.

Values Evaluated as false

Condition expressions can contain values other than booleans (『true』/『false』). The following values are treated as『false』within a condition expression.

ValueDescription
falseThe boolean value『false』itself.
0The integer zero.
0.0The floating-point zero.
""(empty string)A string containing no characters.
"0"The string『"0"』.
[](empty array)An array with no elements.
nullA special value indicating the absence of a value.

All values other than the above are treated as『true』. This includes non-empty strings, numbers other than 0, and arrays with at least one element.

Loose Comparison vs Strict Comparison

PHP's『==』is a loose comparison (with type coercion), while『===』is a strict comparison (without type coercion). Because type coercion can produce unexpected results, use『===』as the default.

Comparison== (loose)=== (strict)
0 == falsetruefalse
0 == ""truefalse
"1" == 1truefalse
null == falsetruefalse
null == 0truefalse
"" == falsetruefalse

Sample Code

if_else_basic.php
<?php
// Determine the available actions based on a KOF character's power gauge
$characterName = "草薙京";
$powerGauge = 80; // value from 0 to 100

// Basic if...elseif...else usage
if ($powerGauge >= 80) {
	echo $characterName . ": MAX super move available\n"; // executed when power gauge is 80 or more
} elseif ($powerGauge >= 50) {
	echo $characterName . ": super move available\n";
} elseif ($powerGauge >= 25) {
	echo $characterName . ": special move available\n";
} else {
	echo $characterName . ": normal attacks only\n";
}

Running the code produces the following output:

php if_else_basic.php
草薙京: MAX super move available
if_else_type_comparison.php
<?php
// Checking the difference between loose (==) and strict (===) comparison
$gauge = 0; // integer 0
$isEmpty = false; // boolean false

// Loose comparison: type coercion causes 0 and false to be considered equal
if ($gauge == $isEmpty) {
	echo "== : gauge and isEmpty are equal\n"; // this branch executes
}

// Strict comparison: int and bool are different types, so they are not equal
if ($gauge !== $isEmpty) {
	echo "!== : gauge and isEmpty differ in type\n"; // this branch executes
}

// Loose comparison between a string number and an integer
$score = "100"; // value received from a form as a string
if ($score == 100) {
	echo "== : string \"100\" and integer 100 are equal (type coercion occurred)\n"; // type coercion occurs
}

// Strict comparison: types differ, so they are not equal
if ($score !== 100) {
	echo "!== : string \"100\" and integer 100 differ in type\n";
}

Running the code produces the following output:

php if_else_type_comparison.php
== : gauge and isEmpty are equal
!== : gauge and isEmpty differ in type
== : string "100" and integer 100 are equal (type coercion occurred)
!== : string "100" and integer 100 differ in type
if_else_nested.php
<?php
// Example of nested conditional branching
$team = "チームヤガミ";
$memberCount = 3;
$isReady = true;

if ($team !== "") {
	if ($memberCount === 3) {
		if ($isReady) {
			echo $team . ": ready for the match\n";
		} else {
			echo $team . ": full roster but still preparing\n";
		}
	} else {
		echo $team . ": only " . $memberCount . " member(s)\n";
	}
} else {
	echo "Team name is not set\n";
}

Running the code produces the following output:

php if_else_nested.php
チームヤガミ: ready for the match
if_else_ternary_match.php
<?php
// The ternary operator writes a simple two-way choice compactly
$hp = 30;
$status = ($hp > 0) ? "fighting" : "KO"; // condition ? value_if_true : value_if_false
echo "Status: " . $status . "\n"; // outputs "Status: fighting"

// match expression (PHP 8 and later) performs strict comparison against multiple values
// Unlike switch, no type coercion occurs
$rank = "S";
$title = match($rank) {
	"S" => "King of Fighters champion",
	"A" => "Elite fighter",
	"B" => "Regular fighter",
	default => "Unranked",
};
echo "Title: " . $title . "\n"; // outputs "Title: King of Fighters champion"

// Situations where if is more appropriate than the ternary operator (when multiple lines are needed)
$powerGauge = 90;
if ($powerGauge >= 80) {
	$message = "MAX super move available";
	$color = "gold";
} else {
	$message = "Normal attacks only";
	$color = "white";
}
echo $message . " (color: " . $color . ")\n";

Running the code produces the following output:

php if_else_ternary_match.php
Status: fighting
Title: King of Fighters champion
MAX super move available (color: gold)
if_else_early_return.php
<?php
// Guard clause pattern: flatten nesting with early return
// Rejecting invalid conditions at the start of a function guarantees preconditions for the rest

// Deeply nested approach (pattern to avoid)
function getSpecialMove_nested(string $characterName, int $powerGauge): string
{
	if ($characterName !== "") {
		if ($powerGauge > 0) {
			if ($powerGauge >= 80) {
				return $characterName . " unleashes the strongest move!";
			} else {
				return $characterName . " uses a normal move";
			}
		} else {
			return "Power gauge is empty";
		}
	} else {
		return "No character selected";
	}
}

// Flat approach using early return (guard clauses)
function getSpecialMove(string $characterName, int $powerGauge): string
{
	// Reject invalid conditions early (guard clauses)
	if ($characterName === "") {
		return "No character selected";
	}
	if ($powerGauge <= 0) {
		return "Power gauge is empty";
	}

	// At this point $characterName and $powerGauge are guaranteed valid
	if ($powerGauge >= 80) {
		return $characterName . " unleashes the strongest move!";
	}
	return $characterName . " uses a normal move";
}

echo getSpecialMove("テリー・ボガード", 100) . "\n"; // gauge is 100, strongest move fires
echo getSpecialMove("不知火舞", 40) . "\n"; // gauge is 40, normal move
echo getSpecialMove("", 80) . "\n"; // empty name, early return
echo getSpecialMove("クラーク・スティル", 0) . "\n"; // gauge is 0, early return

Running the code produces the following output:

php if_else_early_return.php
テリー・ボガード unleashes the strongest move!
不知火舞 uses a normal move
No character selected
Power gauge is empty

Common Mistakes

Writing = where == should be used in a condition expression

Confusing variable assignment (=) with equality comparison (==) inside a condition expression means the branch does not work as intended. Writing = in a condition makes the result of that assignment the condition value.

ng_if_assign.php
<?php
$powerGauge = 80;

// = is assignment. The assignment result (50) becomes the condition, so it is always true
if ($powerGauge = 50) {
	echo "When power gauge is 50: " . $powerGauge . "\n"; // always executes
}

Running the code produces the following output:

php ng_if_assign.php
When power gauge is 50: 50

Use == or === for comparison. = is the assignment operator and should not appear in condition expressions.

ok_if_assign.php
<?php
$powerGauge = 80;
$characterName = "草薙京";

// Use === for strict comparison
if ($powerGauge === 80) {
	echo $characterName . ": MAX super move available\n";
}

Running the code produces the following output:

php ok_if_assign.php
草薙京: MAX super move available

Using else if (with space) instead of elseif

In PHP both else if (with space) and elseif (without space) are valid, but else if expands into the same structure as a nested if. Using elseif as a single word is the common convention.

ng_if_elseif.php
<?php
$rank = "A";

// else if with a space — split notation
if ($rank === "S") {
	echo "King of Fighters champion\n";
} else if ($rank === "A") {
	echo "Elite fighter\n";
} else {
	echo "Regular fighter\n";
}

Running the code produces the following output:

php ng_if_elseif.php
Elite fighter

Writing elseif as one word makes it clear that this is an explicitly chained branch.

ok_if_elseif.php
<?php
$rank = "A";

if ($rank === "S") {
	echo "King of Fighters champion\n";
} elseif ($rank === "A") {
	echo "Elite fighter\n";
} else {
	echo "Regular fighter\n";
}

Running the code produces the following output:

php ok_if_elseif.php
Elite fighter

Summary

The『if』statement evaluates a condition expression and executes the immediately following block if the result is『true』. Condition expressions can contain any value, not just booleans.『false』,『0』,『0.0』,『""』,『"0"』,『[]』, and『null』are treated as『false』; everything else is treated as『true』.

Use『===』(strict comparison) as the default for comparison operators.『==』performs type coercion, so expressions like『0 == false』or『null == 0』evaluate to『true』, producing unexpected results.Use『===』and『!==』, which compare both type and value. For type coercion, see『Type Casting』.

Deep nesting of conditional branches reduces readability. Inside a function, the "guard clause (early return)" pattern is effective: check invalid conditions first and『return』immediately. For simple two-way choices, the ternary operator is an option; for matching against multiple values, the『match』expression available in PHP 8 and later is a useful guide. When variable existence checks are needed, see also『isset() / empty()』.

If you find any errors or copyright issues, please .