CakeFest 2024: The Official CakePHP Conference

elseif/else if

(PHP 4, PHP 5, PHP 7, PHP 8)

elseifは、その名前から分かるように、ifelseの組み合わせです。elseifは、 elseのように、元のif式の値が falseの場合に別の文を実行するようにif 文を拡張します。 しかし、elseとは異なり、elseif式が trueの場合にのみ代わりの式を実行します。 例えば、次のコードは、aはbより大きいaはbに等しいaはbより小さいを出力します。

<?php
if ($a > $b) {
echo
"aはbより大きい";
} elseif (
$a == $b) {
echo
"aはbと等しい";
} else {
echo
"aはbより小さい";
}
?>

複数の elseif を同じ if 文の中で使用することができます。 true と評価された最初の elseif 式を実行します。PHP では、(単語二つで)'else if'と書くこともできます。 動作は(一単語の) 'elseif'と同じです。文法的な意味はやや異なっています (あなたが C 言語に詳しいとすると、C 言語のそれと同じ動作です)。 しかし、最終的な両者の動作は全く同じです。

elseif 文は、前にある全ての if 文と elseif の値が false であり、 現在の elseif 式の値が true である場合にのみ実行されます。

注意: 上の例のように波括弧を使用する限り、 elseifelse if はまったく同じだと考えてよいことに注意しましょう。コロンを使って if/elseif 条件を指定する場合は、 一単語で指定する必要があります。つまり、else if のように分割してはいけません。 分割すると、パースエラーとなってしまいます。

<?php

/* 間違った方法 */
if ($a > $b):
echo
$a." is greater than ".$b;
else if (
$a == $b): // コンパイル不能
echo "The above line causes a parse error.";
endif;


/* 正しい方法 */
if ($a > $b):
echo
$a." is greater than ".$b;
elseif (
$a == $b): // 二つの単語を分割せず組み合わせていることに注目
echo $a." equals ".$b;
else:
echo
$a." is neither greater than or equal to ".$b;
endif;

?>

add a note

User Contributed Notes 1 note

up
-9
Vladimir Kornea
17 years ago
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
echo $a;
else {
echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
echo $a;
}
else:
echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
echo $a;
if($b) {
echo $b;
}
else:
echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.
To Top