Custom Implementation of array_slice Without PHP Built-in Functions
Description
This example shows how to implement the functionality of array_slice manually without using PHP built-in functions. The array_slice function extracts a portion of an array based on the starting index and the length specified. Below, we achieve this using a custom function.
Code Example:
<?php
// Function to mimic array_slice functionality
function customArraySlice($array, $start, $length = null) {
$slicedArray = [];
$arrayLength = count($array);
// Adjust negative start index
if ($start < 0) {
$start = $arrayLength + $start;
}
// Handle no length (slice till the end)
if ($length === null) {
$length = $arrayLength - $start;
}
// Build the sliced array
for ($i = $start; $i < $start + $length && $i < $arrayLength; $i++) {
$slicedArray[] = $array[$i];
}
return $slicedArray;
}
// Test array
$fruits = ["apple", "banana", "cherry", "date", "elderberry"];
// Call the custom function
$result = customArraySlice($fruits, 1, 3);
// Output
echo "Sliced Array: ";
print_r($result);
?>
Output:
Sliced Array: Array
(
[0] => banana
[1] => cherry
[2] => date
)
This manual approach replicates the functionality of array_slice.
It handles both positive and negative starting indices.
The function also works without specifying the length, extracting elements until the end of the array.
Keep Learning 🙂