How to split associative arrays in PHP

Summary:

There are several methods to split an associative array. You can use the array_slice or array_chunk function to split by length. If you want to split the array by key or value then you will need to write a custom function.

PHP has many functions to support different operations related to associative arrays. In this article, we’ll see how to split an associative array in PHP. Associative arrays have keys and values and that’s why there are different ways of splitting them. Based on this fact, we’ll see how to split an array in PHP based on its.

  • Length
  • Keys
  • Values

There’s a lot of things to see so let’s dive in straight to the main topic.

Split array in PHP by length

There are several ways to split an associative array in PHP by length. Here’s an overview of what we’ll see in this section.

  • array_slice function.
  • array_chunk function.

#1 Using array_slice function to split PHP arrays

PHP array_slice function is helpful to split an associative array in PHP based on offset and length values. Let’s see the anatomy of this function.

Description

array_slice() returns the sequence of elements from the array as specified by the offset and length parameters.

Function Signature

array_slice(array $array,int $offset,?int $length = null,bool $preserve_keys = false): array

Arguments

  • $array   – The input array
  • $offset  – The position in the array
  • $length – If the length is positive, the function outputs the sequence from $offset to $length
  • $preserve_keys – Output the associative array with integer keys intact.

Return Type

Returns the sliced array. If $offset is greater than $array length, an empty array is returned.

Example

Here’s an example of how we can split an array in PHP by using offset and length values.

<?php
//An array to be splitted.
$big_array = array("a","b","c","d","e","f","g");
 
//Split array to have elements [a,b,c,d] which means an offset of 0 and length of 4.
$first_split = array_slice($big_array,0,4);
 
//Split array to have elements [e,f,g,h] which mean an offset of 4 and length of 3.
$second_split = array_slice($big_array,4,3);
 
 
/*OUTPUT 
Array       
(
     [0] => a
     [1] => b
     [2] => c
     [3] => d
)
*/
print_r($first_split);
 
 
 
/*OUTPUT
Array       
 (
     [0] => e
     [1] => f
     [2] => g
 )
*/ 
print_r($second_split);
 
?>

Observe the offset and length arguments. These two arguments are crucial for a correct split. Remember that the offset is a position within an array. Since array indexing starts from zero, the offset for the first element will be zero.

Here’s another similar example. Here, we have numeric and integer key values.

<?php
//An array to be splitted.
$big_array = array(
    "Fruit" => "Apple",
    "Vegetable" => "Beetroot",
     7       => "James Bond"
);
 
//Split array to have first two elements, which means an offset of 0 and length of 2.
$first_split = array_slice($big_array,0,2);
 
//Split array to have the last element, which means an offset of 2 and length of 1.
$second_split = array_slice($big_array,2,1);
 
 
/*OUTPUT 
Array       
(
    [Fruit] => Apple       
    [Vegetable] => Beetroot
)
*/
print_r($first_split);
 
 
 
/*OUTPUT
Array       
 (
    [0] => James Bond   
 )
*/ 
print_r($second_split);
 
?>

Works fine, but the only thing noticeable is that it doesn’t preserve the integer key 7 instead reindexes it to zero. How to go about this problem? The answer is $preserve_keys argument, set it to true,, and it preserves the key in the output. Try it out.

#2 Splitting PHP arrays with the array_chunk function

PHP array_chunk function is a function to split associative array in PHP. It outputs an array having partitioned arrays with elements as specified by the length argument. We’ll see how this function works.

Description

Splits array into chunks

Function Signature

array_chunk(array $array, int $length, bool $preserve_keys = false): array

Arguments

  • $array   –  The input array
  • $length –  The size of a partition. The last chunk partition contains less than $length elements.
  • $preserve_keys – Output the associative array with original keys intact.

Return Type

Returns a multi-dimensional array with each array containing less than or equal to $length.

Example

Let’s split the associative array in PHP into two equal partitions. In the example, we have an array with 10 elements and we intend to split it in half.

<?php
//An array to be splitted.
$big_array = array(
    "Element1" => 1,
    "Element2" => 2,
    "Element3" => 3,
    "Element4" => 4,
    "Element5" => 5,
    "Element6" => 6,
    "Element7" => 7,
    "Element8" => 8,
    "Element9" => 9,
     10 => 10,
);
 
//Split array into half
$partitioned_array = array_chunk($big_array,5,true);
 
//Gets the first half.
$first_half  = $partitioned_array[0];
 
//Gets the second half.
$second_half = $partitioned_array[1];
 
/*OUTPUT 
Array
(
    [Element1] => 1
    [Element2] => 2
    [Element3] => 3
    [Element4] => 4
    [Element5] => 5
)
*/
print_r($first_half);
 
/*OUTPUT
Array
(
    [Element6] => 6
    [Element7] => 7
    [Element8] => 8
    [Element9] => 9
    [10] => 10     
)   
*/
print_r($second_half);
?>

The array_chunk outputs a multi-dimensional array containing the two chunks that it had just split. We pass each chunk to a variable. Also, notice that we have set $preserve_keys to true. That’s the reason we get the keys intact in the output.
Next, we’ll see how to split associative arrays in PHP by key.

How to split a PHP array by key

PHP doesn’t have a function to exclusively support splitting an array by key. However, we can use the existing functions in a clever way to get the work done. We’ll be using three PHP functions to split the array in PHP by key. These are array_keys, array_search, and array_chunk.

We’ve already seen the array_chunk function. The array_keys have been used many times in the past few articles. As a refresher, it is a function that returns the array of keys of an associative array. So, array_search is something new for us. 

We won’t be going into the detailed anatomy of the function. To cut a long story short, it searches an array for a given value and returns the first corresponding key, if successful. For readers interested in a detailed review, go checkout PHP documentation.

We’ll define a function using these three building blocks that will take care of all the concerns.

/*
DESCRIPTION: This function splits an array into chunks based on a key value.
 
ARGUMENTS
@Param  $array  array  The Input array  REQUIRED.
@Param  $needle mixed  The key value to split $array on.
@Param  $preserve_keys Boolean  If true, the function preserves the keys after the split
 
RETURNS
    A multi-dimensional array containing the chunks after splitting $array.
    Null if either key value doesn't exist or the chunk length is greater $array length.
*/
function splitArrayByKey($array,$needle,$preserve_keys = false)
{
    //Get the array of keys.
    $array_keys = array_keys($array);
    
    //Search the $needle in the array of keys.
    $split_index = array_search($needle, $array_keys);
 
    //If the keys exists
    if($split_index !== false) 
    {
        //Make array chunks with each chunk containing less than or equal to ($split_index+1) elements.
        $partitioned_array = array_chunk($array,$split_index+1,$preserve_keys);
 
        return $partitioned_array;
    }
 
    //If the key doesn't exist.
    else
    {
        return null;
    }
}

This function splitArrayByKey is our custom function that takes the array and splits it on a key value. 

Here’s how we’ve used this function to split an array in PHP.

//An array to be splitted.
$big_array = array(
    "Element1" => 1,
    "Element2" => 2,
    "Element3" => 3,
    "Element4" => 4,
    "Element5" => 5,
    "Element6" => 6,
    "Element7" => 7,
    "Element8" => 8,
    "Element9" => 9,
     10 => 10,
);
 
//Output of the function.
$partitioned_array = splitArrayByKey($big_array,"Element5",true);
 
 
print_r($partitioned_array);
 
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [Element1] => 1
            [Element2] => 2
            [Element3] => 3
            [Element4] => 4
            [Element5] => 5
        )
 
    [1] => Array
        (
            [Element6] => 6
            [Element7] => 7
            [Element8] => 8
            [Element9] => 9
            [10] => 10
        )
 
)
*/

Cool isn’t it. Let’s now move on to the next section about how to split associative array in PHP by values instead of keys.

Split array in PHP by value

We’ll use the same trick to build a function that would split an array based on a value. However, keep in mind that there could be identical values in an array. For the sake of simplicity, our function makes a split on the first match.

We’ll define a standalone function, splitArrayByValue but it will have a similar logic as we’ve seen in the previous section.

/*
DESCRIPTION: This function splits an array into chunks based on a value.
 
ARGUMENTS
@Param  $array  array  The Input array  REQUIRED.
@Param  $needle mixed  The value to split $array on.
@Param  $preserve_keys Boolean  If true, the function preserves the keys after the split
 
RETURNS
    A multi-dimensional array containing the chunks after splitting $array.
    Null if either the value doesn't exist or the chunk length is greater $array length.
*/
function splitArrayByKey($array,$needle,$preserve_keys = false)
{
    //Get all the values of the $array.
    $array_values = array_values($array);
 
    //Search the $needle in the array.
    $split_index = array_search($needle, $array_values);
 
    //If the value exists
    if($split_index !== false) 
    {
        //Make array chunks with each chunk containing less than or equal to ($split_index+1) elements.
        $partitioned_array = array_chunk($array,$split_index+1,$preserve_keys);
 
        return $partitioned_array;
    }
 
    //If the value doesn't exist.
    else
    {
        return null;
    }
}

Let’s use this function to split an associative array.

//An array to be splitted.
$big_array = array(
    "Employee1" => "Bob",
    "Employee2" => "Martha",
    "Employee3" => "Robert",
    "Employee4" => "David",
    "Employee5" => "Sophie",
    "Employee6" => "Anna"
);
 
//Output of the function.
$partitioned_array = splitArrayByKey($big_array,"Robert",true);
 
 
print_r($partitioned_array);
 
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [Employee1] => Bob   
            [Employee2] => Martha
            [Employee3] => Robert
        )
 
    [1] => Array
        (
            [Employee4] => David 
            [Employee5] => Sophie
            [Employee6] => Anna  
        )
 
)
)
*/

Great! The function works as expected. With this the article comes to the end, we’ve covered a lot of ground and hope you’ve learned something new today. Stay tuned for more interesting articles related to PHP.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.

How to convert associative array to csv in PHP

Add to an array in PHP

Print an array in PHP

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems