LoginSignup
1
0

More than 1 year has passed since last update.

【PHP】for文を使って配列に値を格納する

Posted at

以前作ったポートフォリオアプリの、レコードを作成してDBへ保存する処理。

このコードをふと見ていると、繰り返しの処理がベタ書きされていて気になりました。
for文を使って短縮できたので、メモしておきます。

元のコード

一気に複数の値をDBに保存するため、配列に値をまとめてinsertメソッドを使用しています。

※insertメソッドの注意点
タイムスタンプがnullとなる、複数代入から保護されていないのでセキュリティ的に危険というデメリットもあります。今回はユーザーからの入力の可能性がないので、insertメソッドを使うこととします。

$players = [
          ["name" => null,
          "room_id" => $room_id,
          "user_id" => 1],
          ["name" => null,
          "room_id" => $room_id,
          "user_id" => 2],
          ["name" => null,
          "room_id" => $room_id,
          "user_id" => 3],
          ["name" => null,
          "room_id" => $room_id,
          "user_id" => 4]
        ];

RoomPlayer::insert($players);

ループ処理(for)を使う

今回の例では4レコードの作成と決まっているので、元のコードでも記述は可能でしたが、件数が増えるほどにループ処理を使う必要性は増します。

$players = [];

for ($i=0; $i<4; $i++){
  $players[] = [
     "name" => null,
     "room_id" => $room_id,
     "user_id" => $i+1
     ];
}

RoomPlayer::insert($players);

以上、覚え書きでした(^^)/

1
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
1
0