PHP Program to Merge two Sorted Arrays
Given two sorted arrays, i.e. arr1, and arr2, the task is to merge both sorted arrays and make a single sorted array.
Examples:
Input: arr1 = [1, 3, 5, 7, 8]
arr2 = [2, 3, 4, 5, 6]
Output: [1, 2, 3, 3, 4, 5, 6, 7, 8]
There are two methods to merge both arrays, these are:
Table of Content
- Using Loop
- Using array_merge() Function
Using Loop
Here, we iterate through both arrays and compare array elements to merge them into a new sorted array.
Example:
PHP
<?php 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 ++; } } while ( $i < count ( $arr1 )) { $mergedArray [] = $arr1 [ $i ]; $i ++; } while ( $j < count ( $arr2 )) { $mergedArray [] = $arr2 [ $j ]; $j ++; } return $mergedArray ; } $arr1 = [1, 3, 5, 7]; $arr2 = [2, 4, 6, 8]; $newArray = mergeArrays( $arr1 , $arr2 ); echo "Merged Sorted Array: " . implode( ", " , $newArray ); ?> |
Output
Merged Sorted Array: 1, 2, 3, 4, 5, 6, 7, 8
Using array_merge() Function
The array_merge() function is used to merge two or more arrays into a single array. After merging the both arrays, we use sort() function to sort the merged array in ascending order.
Example:
PHP
<?php function mergeArrays( $arr1 , $arr2 ) { $mergedArray = array_merge ( $arr1 , $arr2 ); sort( $mergedArray ); return $mergedArray ; } $arr1 = [1, 3, 5, 7]; $arr2 = [2, 4, 6, 8]; $newArray = mergeArrays( $arr1 , $arr2 ); echo "Merged Sorted Array: " . implode( ", " , $newArray ); ?> |
Output
Merged Sorted Array: 1, 2, 3, 4, 5, 6, 7, 8
Contact Us