PHPのお勉強!

PHP TOP

制御構造に関する別の構文

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

PHPは、いくつかの制御構造、つまり、ifwhileforforeachswitch に関する別の構文を提供します。 各構造において開き波括弧をコロン(:)、閉じ波括弧をそれぞれ endif;,endwhile;, endfor;,endforeach;, endswitch;に変更するのが 別の構文の基本的な形式となります。

<?php if ($a == 5): ?>
Aは5に等しい
<?php endif; ?>

上の例では、HTML ブロック "Aは5に等しい" はこの構文で 書かれた if 文の内部で入れ子になっています。 この HTML ブロックは、$a が 5 の場合にのみ表示されます。

この方法は、elseelseif にも同様に適用することができます。 次の例は、この形式で if 文を elseif および else とともに使用しています。

<?php
if ($a == 5):
echo
"aは5に等しい";
echo
"...";
elseif (
$a == 6):
echo
"aは6に等しい";
echo
"!!!";
else:
echo
"aは5でも6でもない";
endif;
?>

注意:

同じブロック内で別の構文を混ぜて使うことはできません。

警告

switch 文と最初の case の間で何か (空白文字も含む) を出力すると、構文エラーになります。 たとえば、以下のコードは無効です。

<?php switch ($foo): ?>
<?php case 1: ?>
...
<?php endswitch; ?>

一方、以下のコードは有効です。というのも、 switch 文の行末の改行文字は終了タグ ?> の一部と見なされるため、 switchcase の間では何も出力されないからです。

<?php switch ($foo): ?>
<?php
case 1: ?>
...
<?php endswitch; ?>

whilefor、および if に、より多くの例があります。

add a note

User Contributed Notes 2 notes

up
27
toxyy
2 years ago
I feel compelled to give a more elegant way using heredoc than the other comment:

<ul>
<?php foreach($list as $item): echo
<<<ITEM
<li id="itm-$item[number]">Item $item[name]</li>
ITEM;
endforeach;
?>
</ul>

Which works better with multi line blocks, as you only need one overall php tag.

(please don't omit the closing </li> tag despite it being legal, personal preference)
up
-1
sedaratifarzaneh4 at gmail dot com
8 days ago
When embedded statement in hosts connected to accounts for payments to be entered or direct deposits for payrolls to be done what is the proper format for each thing look like again? I'm having trouble remembering everything with my amnesia. I have some direct deposits I want to change and a new hash tag string account I need to add a button to my webpage for creating random hashes for different signature account on file encodings to get transfers assets into another accounts. Also new utilities to be paid in addition to regular utilities and rent each month.
To Top