To get a sub-array in PHP, you can use the `array_slice` function.
In this example,
$numbers
with some values.array_slice
function to get a sub-array from index 2 to index 4 (exclusive).array_slice
function returns a new array with the specified range.<?php
$numbers = [1, 2, 3, 4, 5];
$subArray = array_slice($numbers, 2, 2);
echo 'Sub-array: ' . json_encode($subArray);
?>
Sub-array: [3,4]
In this example,
$colors
with some values.array_slice
function to get a sub-array from index 1 to index 3 (exclusive).array_slice
function returns a new array with the specified range.<?php
$colors = ['red', 'green', 'blue', 'yellow', 'orange'];
$subArray = array_slice($colors, 1, 2);
echo 'Sub-array: ' . json_encode($subArray);
?>
Sub-array: ["green","blue"]
In this tutorial, we learned How to get Sub Array in PHP language with well detailed examples.