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?

More than 3 years have passed since last update.

PHPでforeachを使って配列を操作してみましょう!

Posted at

#foreach


配列の要素を、foreachを使って1つ1つ取り出してみます。

index.php
<?php
$scores = [
  '1番目' => 1,
  '2番目' => 2,
  '3番目' => 3,
];

foreach ($scores as $score) {
  echo $score . PHP_EOL;
}

以下をターミナルに入力します。
~$ php index.php

1つずつ出力されました。
~ $ php main.php
1
2
3
~ $ 

キーも一緒に取り出してみます。

$key => 追加します。

index.php

<?php
$scores = [
  '1番目' => 1,
  '2番目' => 2,
  '3番目' => 3,
];

foreach ($scores as $key => $score) { 
  echo $key . ' は ' . $score . PHP_EOL;   //文字列で繋げて表示させます。
}

ターミナルで以下を実行します。
~$ php index.php

キーも出力されました ☆
~ $ php index.php
1番目 は 1
2番目 は 2
3番目 は 3
~ $ 
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?