Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to explode string like a pagination?

For example:

$string = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15';

And then explode it like a pagination, for example 8 values each row will result in two 2 pages:

$arr = p_explode(',', $string, 8);
array(
    0 => "1,2,3,4,5,6,7,8"
    1 => "9,10,11,12,13,14,15"
) 

Or maybe explode for example into 5 values each row will result into 3 pages:

$arr = p_explode(',',$string,5);
array(
    0 => "1,2,3,4,5"
    1 => "6,7,8,9,10"
    2 => "11,12,13,14,15"
) 

Where p_explode would be:

p_explode(string_delimiter, string_string, int_number_values_each_page)

Is it possible?

like image 323
Diogo Garcia Avatar asked Mar 08 '23 02:03

Diogo Garcia


1 Answers

Use the array_chunk() and explode() PHP's functions:

$elementsPerPage = 5;
$arrayOfPages = array_chunk(explode(',', $string), $elementsPerPage);
print_r($arrayOfPages);

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )

    [1] => Array
        (
            [0] => 6
            [1] => 7
            [2] => 8
            [3] => 9
            [4] => 10
        )

    [2] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 13
            [3] => 14
            [4] => 15
        )

)

array_chunk() splits an array into chunks.

explode() splits a string by string, in that case create an array made by all numbers contained in $string dividing them by ,.

like image 74
user2342558 Avatar answered Mar 15 '23 06:03

user2342558