How to Implement array_push in PHP Without Using Built-In Functions

The array_push function in PHP adds one or more elements to the end of an array. While this built-in function is highly efficient, understanding how to implement it manually can improve your coding skills and help in scenarios where built-in functions are not allowed. This guide explains how to create your own array_push function in PHP.

What Is array_push?

The array_push function appends elements to an array and updates its length. For example:

$array = [1, 2];
array_push($array, 3, 4);  
// Result: [1, 2, 3, 4]

We will recreate this functionality without using PHP’s built-in array functions.

Step 1: Define the Custom Function

Here’s a simple implementation of a custom array_push function:

function customArrayPush(&$array, ...$values) {
    // Loop through each value to add
    foreach ($values as $value) {
        // Add the value to the next available index
        $array[count($array)] = $value;
    }
    
    // Return the new count of the array
    return count($array);
}

Step 2: Test the Custom Function

Here’s how to use the custom array_push function:

// Example 1: Add a single element
$numbers = [1, 2, 3];
$newCount = customArrayPush($numbers, 4);
echo "New Array: ";
print_r($numbers);
echo "New Count: " . $newCount . "\n";

// Example 2: Add multiple elements
$newCount = customArrayPush($numbers, 5, 6, 7);
echo "New Array: ";
print_r($numbers);
echo "New Count: " . $newCount . "\n";

Output:

New Array: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
New Count: 4

New Array: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)
New Count: 7

How It Works

  1. The function accepts the array by reference (&$array) to modify it directly.
  2. The …$values parameter allows multiple elements to be passed to the function.
  3. Each value is added to the array at the next available index (count($array)).
  4. The function returns the new count of the array.

Step 3: Handle Edge Cases

To make the function more robust:

  1. Ensure $array is an array before attempting to modify it.
  2. Validate that the added values are of the desired type (optional).

By implementing your own array_push function, you gain a deeper understanding of PHP arrays and how they work under the hood. While using PHP’s built-in functions is more practical in production, custom solutions are invaluable for learning and special use cases.

For more PHP tutorials and programming tips, check out our blog!

Keep Learning 🙂

Leave a Reply

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