入れ子(ネスト)で多階層にしたforeach文において、複数の階層のループ(繰り返し)処理を終了させたいときは、breakの引数に、終了させたい階層数を指定する。
サンプル
多次元配列の各要素の値を取得
<?php
$varArrayA = array(
array(
"red" => "レッド",
"blue" => "ブルー",
"yellow" => "イエロー"
),
array(
"aka" => "赤色",
"ao" => "青色",
"ki" => "黄色"
)
);
foreach ( $varArrayA as $varValueA ) {
foreach ( $varValueA as $varValueB ) {
echo '<p>' . $varValueB . '</p>';
if ( $varValueB == 'ブルー' ) {
break 2;
}
}
}
?>
$varArrayA = array(
array(
"red" => "レッド",
"blue" => "ブルー",
"yellow" => "イエロー"
),
array(
"aka" => "赤色",
"ao" => "青色",
"ki" => "黄色"
)
);
foreach ( $varArrayA as $varValueA ) {
foreach ( $varValueA as $varValueB ) {
echo '<p>' . $varValueB . '</p>';
if ( $varValueB == 'ブルー' ) {
break 2;
}
}
}
?>
↓↓↓出力結果↓↓↓
レッド
ブルー
ブルー
多次元配列の各要素のキーと値を取得
<?php
$varArrayA = array(
array(
"red" => "レッド",
"blue" => "ブルー",
"yellow" => "イエロー"
),
array(
"aka" => "赤色",
"ao" => "青色",
"ki" => "黄色"
)
);
foreach ( $varArrayA as $varValueA ) {
foreach ( $varValueA as $varKeyB => $varValueB ) {
echo '<p>';
echo $varKeyB . ': ' . $varValueB;
echo '</p>';
if ( $varKeyB == 'blue' ) {
break 2;
}
}
}
?>
$varArrayA = array(
array(
"red" => "レッド",
"blue" => "ブルー",
"yellow" => "イエロー"
),
array(
"aka" => "赤色",
"ao" => "青色",
"ki" => "黄色"
)
);
foreach ( $varArrayA as $varValueA ) {
foreach ( $varValueA as $varKeyB => $varValueB ) {
echo '<p>';
echo $varKeyB . ': ' . $varValueB;
echo '</p>';
if ( $varKeyB == 'blue' ) {
break 2;
}
}
}
?>
↓↓↓出力結果↓↓↓
red: レッド
blue: ブルー
blue: ブルー