To split an array in PHP, you can use the array_chunk function or array_slice function.
In this example,
$numbers
with integer elements.array_chunk
function to split $numbers
into chunks of a specified size.array_chunk
function returns an array of chunks.<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunks = array_chunk($numbers, 3);
print_r($chunks);
?>
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 [1] => 8 [2] => 9 ) )
In this example,
$numbers
with integer elements.array_slice
function to extract a slice of $numbers
based on indices.array_slice
function returns an array representing the sliced elements.<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$slice1 = array_slice($numbers, 0, 3);
$slice2 = array_slice($numbers, 3, 3);
$slice3 = array_slice($numbers, 6, 3);
print_r([$slice1, $slice2, $slice3]);
?>
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 [1] => 8 [2] => 9 ) )
In this tutorial, we learned How to Split an Array in PHP language with well detailed examples.