Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,003 questions

51,950 answers

573 users

How to merge two sorted arrays in PHP

1 Answer

0 votes
function mergeArrays($arr1, $arr2) {
    $mergedArray = [];
    $i = $j = 0;

    while ($i < count($arr1) && $j < count($arr2)) {
        if ($arr1[$i] < $arr2[$j]) {
            $mergedArray[] = $arr1[$i];
            $i++;
        } else {
            $mergedArray[] = $arr2[$j];
            $j++;
        }
    }

    // Add remaining elements
    while ($i < count($arr1)) {
        $mergedArray[] = $arr1[$i];
        $i++;
    }
    while ($j < count($arr2)) {
        $mergedArray[] = $arr2[$j];
        $j++;
    }

    return $mergedArray;
}

$arr1 = [1, 3, 5, 7, 8, 9, 9];
$arr2 = [2, 3, 4, 5, 6, 9];

print_r(mergeArrays($arr1, $arr2));



/*
run:

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

*/

 



answered Nov 29, 2025 by avibootz

Related questions

...