array_splice Without PHP Built-in Functions
Description
This tutorial demonstrates how to manually implement the functionality of array_splice without using PHP built-in functions. The array_splice function removes a portion of an array and replaces it with new elements, reindexing the array. Below, we achieve this using a custom approach.
Code Example:
<?php
// Function to mimic array_splice functionality
function customArraySplice(&$array, $offset, $length = null, $replacement = []) {
$removedElements = [];
$newArray = [];
$arrayLength = count($array);
// Adjust negative offset
if ($offset < 0) {
$offset = $arrayLength + $offset;
}
// Handle null length (remove all elements after offset)
if ($length === null) {
$length = $arrayLength - $offset;
}
// Build the removed elements array and the new array
for ($i = 0; $i < $arrayLength; $i++) {
if ($i >= $offset && $i < $offset + $length) {
$removedElements[] = $array[$i];
} else {
$newArray[] = $array[$i];
}
}
// Insert replacement elements at the correct position
$array = array_merge(
array_slice($newArray, 0, $offset), // Elements before offset
$replacement, // Replacement elements
array_slice($newArray, $offset) // Elements after offset
);
return $removedElements; // Return removed elements
}
// Test array
$fruits = ["apple", "banana", "cherry", "date", "elderberry"];
// Call the custom function
$removed = customArraySplice($fruits, 1, 2, ["grape", "fig"]);
// Output
echo "Removed Elements: ";
print_r($removed);
echo "Modified Array: ";
print_r($fruits);
?>
Output:
Removed Elements: Array
(
[0] => banana
[1] => cherry
)
Modified Array: Array
(
[0] => apple
[1] => grape
[2] => fig
[3] => date
[4] => elderberry
)
This manual approach replicates array_splice functionality.
Handles both positive and negative offsets.
Supports replacing removed elements with new values.
Returns the removed portion while updating the original array.
Keep Learning 🙂