clock  Mon - Sun 8.00 AM - 8.00 PM
fb
instagram
play store
pinterest

Group of Array in PHP Laravel

writter  Sumit Dey Sarkar
Date  13 Sep 2022
Language  Laravel
Group of Array in PHP Laravel

Group of Array in PHP Laravel

In this tutorial we are going to create a function for grouping the array data in custom group.

function array_group($arr, $groupIn)
    {
        $count =  intval(ceil(count($arr) / $groupIn));
        $new_arr = [];
        for ($i = 0; $i < $count; $i++) {
            $temp_arr = [];
            for ($a = $i * $groupIn; $a < $i * $groupIn + $groupIn; $a++) {
                if (isset($arr[$a])) {
                    $temp_arr[] = $arr[$a];
                }
            }
            $new_arr[] = $temp_arr;
        }
 
        return $new_arr;
    }

 

For example -

$arr =  [
        "rhavyn@aol.com",
        "garyjb@icloud.com",
        "crowl@att.net",
        "jhardin@mac.com",
        "ijackson@outlook.com",
        "jigsaw@outlook.com",
        "sjmuir@icloud.com",
        "philb@outlook.com",
        "barnett@gmail.com",
        "rnewman@comcast.net",
        "pedwards@sbcglobal.net",
        "dogdude@yahoo.com"
    ];
 
    dd(array_group($arr, 5));

 

Output

laravel