0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP foreach文

Last updated at Posted at 2025-12-16

phpのforeach文に基本について

foreachは配列やオブジェクトを簡単にループするためのもの。for文と違いカウンター変数を管理する必要がない。

基本構造

  • valueのみのパターン
foreach (反復可能なオブジェクト as ループした値を格納する変数) {
    // 各要素に対して実行されるコード
}
  • キーと値のパターン
foreach (反復可能なオブジェクト as $キー => $値) {
    // 各要素に対して実行されるコード
}

例:

<?php
$prices = [
    "りんご" => 150,
    "バナナ" => 80,
    "みかん" => 100
];

foreach ($prices as $fruit => $price) {
    echo $fruit . "の価格は" . $price . "円です<br>";
}
/* 出力:
りんごの価格は150円です
バナナの価格は80円です
みかんの価格は100円です
*/
?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?