Home > OS >  Clean way to divide one array to two arrays in Laravel 8
Clean way to divide one array to two arrays in Laravel 8

Time:12-07

I want to divided my $request->all() array into two arrays so I can send both arrays into a different database table.

This is what I receive:

  array:12 [▼
  "key1" => "value1"
  "key2" => "value2"
  "key3" => "value3"
  "key4" => "value4"
  "key5" => "value5"
  "key6" => "value6"
  "key7" => "value7"
  "key8" => "value8"
  "key9" => "value9"
  "key10" => "value10"
  "_token" => "47p7eZpSOVOP0kSrL1HBSXn2OrvYT1kCiNoR2Ekr"
  "submit" => "Save"
  ]

But I want two different arrays, like so:

  array:5 [▼
  "key1" => "value1"
  "key2" => "value2"
  "key3" => "value3"
  "key4" => "value4"
  "key5" => "value5"
  ]

And:

array:7 [▼
  "key6" => "value6"
  "key7" => "value7"
  "key8" => "value8"
  "key9" => "value9"
  "key10" => "value10"
  "_token" => "47p7eZpSOVOP0kSrL1HBSXn2OrvYT1kCiNoR2Ekr"
  "submit" => "Save"
  ]

How can I achieve this? I already had something in mind for the first array but I don't know how to get the second one. This is what I have:

$first_array = [];
$second_array = [];

foreach ($request->all() as $key => $value) {
    $first_array[$key] = $value;

    if ($key == 'key6') {
        break;
    }
}

CodePudding user response:

You can use array_slice() as you say you want to split the array into the first 5 and then all the rest.

$input = [  "key1" => "value1",
            "key2" => "value2",
            "key3" => "value3",
            "key4" => "value4",
            "key5" => "value5",
            "key6" => "value6",
            "key7" => "value7",
            "key8" => "value8",
            "key9" => "value9",
            "key10" => "value10",
            "_token" => "47p7eZpSOVOP0kSrL1HBSXn2OrvYT1kCiNoR2Ekr",
            "submit" => "Save"
];

$p1 = array_slice($input, 0, 5);

$p2 = array_slice($input, 5); 

print_r($p1);
print_r($p2);

RESULTS

Array
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
    [key4] => value4
    [key5] => value5
)
Array
(
    [key6] => value6
    [key7] => value7
    [key8] => value8
    [key9] => value9
    [key10] => value10
    [_token] => 47p7eZpSOVOP0kSrL1HBSXn2OrvYT1kCiNoR2Ekr
    [submit] => Save
)

CodePudding user response:

Array chunk doesnt do the trick but this one works:

$first_array = [];
$second_array = [];
$count = 0;

foreach ($request->all() as $key => $value) {
    if ($count <= 7) {
        $first_array[$key] = $value;
    } else {
        $second_array[$key] = $value;
    }

    $count  ;
}

dd($first_array);

  • Related