Group of Array in PHP Laravel

AuthorSumit Dey Sarkar

Pubish Date13 Sep 2022

categoryLaravel

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

Comments 0

Leave a comment