Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

array_partition function #14582

Closed
remco-pc opened this issue Jun 16, 2024 · 1 comment
Closed

array_partition function #14582

remco-pc opened this issue Jun 16, 2024 · 1 comment

Comments

@remco-pc
Copy link

remco-pc commented Jun 16, 2024

Description

this function is like array_chunk, but instead of making it chunk size, it will use partition.

The difference with array_chunk is that it chunks the elements in a multidimensional array up to size.

function array_partition($array=[], $size=1, $preserve_keys=false): array
    {
        $array = (array) $array;
        $size = (int) $size;
        if($size < 1){
            throw new Exception('Size must be greater than 0');
        }
        $result = [];
        $partition = [];
        $counter = 0;
        $count = count($array);
        $amount = (int) ceil($count / $size);
        if($preserve_keys === false){
            foreach ($array as $value) {
                $partition[] = $value;
                $counter++;
                if ($counter === $amount) {
                    $result[] = $partition;
                    $partition = [];
                    $counter = 0;
                }
            }
        } else {
            foreach ($array as $key => $value) {
                $partition[$key] = $value;
                $counter++;
                if ($counter === $amount) {
                    $result[] = $partition;
                    $partition = [];
                    $counter = 0;
                }
            }
        }
        if(!empty($partition)){
            $result[] = $partition;
        }
        return $result;
    }
$partition = array_partition($array, 2);

results in

$partition = [
0 => [...],
1 => [...]
]
@remco-pc
Copy link
Author

remco-pc commented Jun 17, 2024

found my oneliner:

$chunks = array_chunk($list, ceil(count($list) / $threads));

so function could be:

/**
     * @throws Exception
     */
    function array_partition($array=[], $size=1, $preserve_keys=false): array
    {
        $array = (array) $array;
        $size = (int) $size;
        if($size < 1){
            throw new Exception('Size must be greater than 0');
        }
        return array_chunk($array, ceil(count($array) / $size), $preserve_keys);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant