Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to divide an array into smaller arrays

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.27k
    Comment on it

    This article demonstrates about some PHP functions which can be used to divide an array into smaller arrays. The list and details of each function are given below :

    1. array_chunk() :

    array_chunk() splits an array into smaller chunks(arrays) of specified size except last chunk, last chunk size can be smaller than the specified size.

     

    Syntax : array_chunk(array, chunk_size, preserve_key)

    array : Specifies an array to split.(Required)

    chunk_size : An integer defines the size of the chunks.(Required)

    preserve_key : A boolean value.(Optional)

    If TRUE is set as value for preserve_key parameter, then the function keeps the original array index in chunks. The default value is FALSE which will reindex the keys for new chunks. Each chunk index starts from 0.

     

    Description : array_chunk() divides an array into smaller arrays (chunks) of specified size (chunk_size). Only the last array can be smaller than the specified size.

     

    Result : The function returns a multidimensional array which contains a chunk (split array) of specified chunk_size on each dimension. Each chunked array has numerical indexes starting from 0, if preserve_key parameter is not set TRUE.

     

    Note : If the value of chunk_size is smaller than 1 then the function returns NULL and generates E_WARNING.

     

    Example :

    <?php
    $arr = array('orange', 'apple', 'mango', 'pear', 'grapes');
    echo "<pre>";
    print_r(array_chunk($arr, 2));
    echo "<br>With preserved key : <br>";
    print_r(array_chunk($arr, 2, true));
    echo "</pre>";
    ?>

    Output :

    Array
    (
        [0] => Array
            (
                [0] => orange
                [1] => apple
            )
        [1] => Array
            (
                [0] => mango
                [1] => pear
            )
        [2] => Array
            (
                [0] => grapes
            )
    )
    With preserved key :
    Array
    (
        [0] => Array
            (
                [0] => orange
                [1] => apple
            )
        [1] => Array
            (
                [2] => mango
                [3] => pear
            )
        [2] => Array
            (
                [4] => grapes
            )
    )

     

     

    2. array_slice() :

    array_slice() function is used to extract a slice (an array of selected elements) from an array.

     

    Syntax : array_slice(array, start_index,length,preserve_key)

    array : Specifies an array.(Required)

    start_index : An integer value which defines the starting index for slicing.(Required)

    length : This parameter specifies the number of elements to extract.(Optional)

    preserve_key : A boolean value. If it is set TRUE the function keeps the original index in sliced array. As default functionality this parameter is set as FALSE and function will reset the numerical indexes of sliced array. (Optional)

     

    Description : array_slice() function returns an array of extracting elements from the array by using start_index and length parameters. 

     

    If start_index is a positive integer than the slicing starts from given index, for example start index has value equals to 1 that means slicing starts from index 1. If it is negative integer than slicing starts from that element which far from end of the array. For example with value -2 slicing starts from the second last element of array.

     

    length is an optional parameter which defines the number of elements to be extracted from the array. If it is skipped, then this function extracts all the elements from index defined by start_index upto last index of array.

     

    If length value is positive, then the function extracts elements from index defined by start_index upto to the length count. If length value is negative, then the slicing will stop that many elements from the end of the array. If the size of the array is smaller than the length value, then only available array elements sliced from the array.

     

    Result : Returns an array of selected elements.

     

    Note :

    1. For string keys, array_slice() function always preserve the keys.

    2. From PHP version 5.0.2 preserve_key parameter was added.

    3. From PHP version 5.2.4 the default value for length parameter is set to NULL and the function takes it as array length. Prior to this version the default value for length parameter is 0 and function will not return anything.

     

    Example1 :

    <?php
    $arr=array("1" => "orange", "4" =>"apple", "5" => "mango", "7" => "pear", "8" => "grapes");
    echo "With only start_index : <br>";
    echo "<pre>";
    print_r(array_slice($arr,2));
    echo "</pre>";
    echo "<br>With length : <br>";
    echo "<pre>";
    print_r(array_slice($arr,2,2));
    echo "</pre>";
    ?>

    Output :

     

    With only start_index :
    Array
    (
        [0] => mango
        [1] => pear
        [2] => grapes
    )
    With length :
    Array
    (
        [0] => mango
        [1] => pear
    )

     

    Example 2 : With negative parameters

    <?php
    $arr=array("1" => "orange", "4" => "apple", "5" => "mango", "7" => "pear", "8" => "grapes");
    echo "With negative start_index : <br>";
    echo "<pre>";
    print_r(array_slice($arr,-2));
    echo "</pre>";
    echo "<br>With negative length : <br>";
    echo "<pre>";
    print_r(array_slice($arr,2,-1));
    echo "</pre>";
    ?>

    Output :

    With negative start_index :
    Array
    (
        [0] => pear
        [1] => grapes
    )
    With negative length :
    Array
    (
        [0] => mango
        [1] => pear
    )

     

    Example 3 : With preserve_key parameter

    <?php
    $arr1=array("1" => "orange", "4" => "apple", "5" => "mango", "7" => "pear", "8" => "grapes");
    echo "Without preserve_key parameter(false) : <br>";
    echo "<pre>";
    print_r(array_slice($arr1,2,2));
    echo "</pre>";
    echo "<br>With preserve_key parameter(True) : <br>";
    echo "<pre>";
    print_r(array_slice($arr1,2,2,1));
    echo "</pre>";
    $arr2=array("a" => "orange", "b" => "apple", "c" => "mango", "d" => "pear", "e" => "grapes");
    echo "<br>Without numeric keys : <br>";
    echo "<pre>";
    print_r(array_slice($arr2,2,2));
    echo "</pre>";
    ?>

    Output :

    Without preserve_key parameter(false) :
    Array
    (
        [0] => mango
        [1] => pear
    )
    With preserve_key parameter(True) :
    Array
    (
        [5] => mango
        [7] => pear
    )
    Without numeric keys :
    Array
    (
        [c] => mango
        [d] => pear
    )

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: