array_shift Without PHP Built-in Functions

Description

This example demonstrates how to implement the functionality of array_shift manually without using any built-in PHP array functions. The array_shift function removes the first element from an array and reindexes the remaining elements. Here, we achieve this using a custom function.

Code Example:

<?php
// Function to manually remove the first element of an array
function customArrayShift(&$array) {
    if (empty($array)) {
        return null; // Return null if the array is empty
    }
    
    $firstElement = $array[0]; // Store the first element
    $newArray = [];
    
    // Reindex the array manually
    for ($i = 1; $i < count($array); $i++) {
        $newArray[$i - 1] = $array[$i];
    }
    
    // Replace original array with the new array
    $array = $newArray;
    
    return $firstElement; // Return the removed element
}

// Test array
$fruits = ["apple", "banana", "cherry", "date"];

// Call the custom function
$removedElement = customArrayShift($fruits);

// Output
echo "Removed Element: " . $removedElement . "\n";
echo "Remaining Array: ";
print_r($fruits);
?>
Removed Element: apple
Remaining Array: Array
(
    [0] => banana
    [1] => cherry
    [2] => date
)

  This manual approach mimics the functionality of array_shift.

  It ensures the first element is removed, and the remaining elements are reindexed properly.

  Suitable for scenarios where built-in functions are restricted.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *