「php入門」foreach繰り返し処理のサンプルコード

例1 valueのみ

$a = array(1, 2, 3, 23);

foreach ($a as $v) {
echo “Current value of $a: $v. “;
}
例2

$a = array(1, 2, 3, 23);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
echo “$a[$i] => $v. “;
$i++;
}
例3 keyとvalue

$a = array(
“one" => 12,
“two" => 22,
“three" => 13,
“seventeen" => 37
);

foreach ($a as $k => $v) {
echo “$a[$k] => $v. “;
}
例4 多次元配列
$a = array();
$a[0][0] = “cft1";
$a[0][1] = “cft2";
$a[1][0] = “cft3";
$a[1][1] = “cft4";

foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo “$v2 “;
}
}

例5 動的配列

foreach (array(3, 4, 6, 7, 8) as $gd) {
echo “$gd";
}
?>

PHP

Posted by arkgame