Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Bunnypants's avatar

Dynamically storing arrays using key

I have dynamically created inputs and stored them in an array with their iteration in the loop as their key . What I need to do is store the values with the same array key from the three arrays as single row in my table. Any ideas?

Here's the dump of the $request

array:11 [▼
  "_token" => "ess85qzcEEBcP9oRg61v6YCEiRj3HVM6650pSFr9"
  "gradelevel" => "Grade 12"
  "strand" => "ICT"
  "section_number" => "12"
  "lowergrade_limit" => "87"
  "uppergrade_limit" => "89"
  "adviser" => "1"
  "subject_teachers" => array:3 [▼
    3 => "2"
    4 => "10"
    5 => "10"
  ]
  "day" => array:3 [▼
    3 => "Monday"
    4 => "Monday"
    5 => "Monday"
  ]
  "starts_at" => array:3 [▼
    3 => "00:43"
    4 => "02:41"
    5 => "03:42"
  ]
  "ends_at" => array:3 [▼
    3 => "01:41"
    4 => "03:41"
    5 => "01:41"
  ]
]
0 likes
6 replies
sr57's avatar

in my table

What is its structure?

Bunnypants's avatar

@sr57 I'm creating a new row in "sections" which has many "teachers_subjects_schedules" which is where I want to store those arrays. "teachers_subjects_schedules" has one "sections". I hope that makes sense I'm new to this.

hafiq88's avatar
hafiq88
Best Answer
Level 1

I assume you are talking to store subject_teachers array along with day, starts_at, and ends_at array.

$input = $request->all();
foreach($input['subject_teachers '] as $index => $teacher) {
     Subject::create([
            'teacher_id' => $teacher,
            'day' => $input['day'][$index],
            'starts_at' => $input['starts_at'][$index],
            'ends_at' => $input['ends_at'][$index]
      ])
}
1 like
Bunnypants's avatar

@hafiq88 Thanks! This looks like something I can work with. I have a problem though, normally I can just identify the index by the iteration of the for loop but as you see the keys don't really follow a numerical order .Any suggestions on how I can properly get the indexes?

Please or to participate in this conversation.