phparraysassociative-array

Append data to associative array in PHP


I am using push function to append my items to an array in PHP

 foreach($request->input('students') as $student) {
        
            $rules[] = [$students['name'] => 'required'];
  } 

when i print the rules it outputs something like this, :

Array
(
    [0] => Array
        (
            [Amit]=> required
        )

    [1] => Array
        (
            [James] => required
        )
)

but i want it's structure like, i want to remove its indexes to make it complete associative:

   Array
        (
            [Amit]=> required
        )

     Array
        (
            [James] => required
        )

Solution

  • what you have and what you want is both the same structure, most probably you want this:

    foreach($request->input('students') as $student) {
         $rules[$student['name']] =  'required';
    } 
    

    which outputs with:

    Array
    (
        [Amit] => required
        [James] => required
    )
    

    Note it's hard to guess without knowing your $request->input('students') structure...