How to Create a PHP Function for Merging Arrays Without Built-In Functions

The array_merge function in PHP combines the elements of two or more arrays into one array. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_merge(...$arrays) {
    $result = []; // Initialize an empty array to store the merged values

    // Loop through each input array
    foreach ($arrays as $array) {
        // Loop through the current array
        foreach ($array as $key => $value) {
            $result[] = $value; // Add the value to the result array
        }
    }

    return $result;
}

// Example usage
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];

$mergedArray = custom_array_merge($array1, $array2, $array3);
print_r($mergedArray);
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

Explanation:

  1. Input Parameters:
    • Accepts a variable number of arrays using …$arrays.
  2. Result Initialization:
    • Create an empty $result array to store the merged values.
  3. Outer Loop:
    • Loop through each input array in $arrays.
  4. Inner Loop:
    • Iterate through the current array and append its values to $result.
  5. Return Value:
    • Return the $result array containing all elements from the input arrays.

Keep Learning 🙂

Leave a Reply

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