PHP Array Exercises : Merge two arrays
11. Merge Arrays by Index
Write a PHP program to merge (by index) the following two arrays.
Sample arrays :
$array1 = array(array(77, 87), array(23, 45));
$array2 = array("w3resource", "com");
Sample Solution:
PHP Code:
<?php
// Define a multidimensional array $array1
$array1 = array(array(77, 87), array(23, 45));
// Define a simple array $array2
$array2 = array("w3resource", "com");
// Define a function named 'merge_arrays_by_index' that merges elements based on their indexes
function merge_arrays_by_index($x, $y)
{
// Create an empty temporary array
$temp = array();
// Add the first element $x to the temporary array
$temp[] = $x;
// Check if $y is a scalar value
if (is_scalar($y))
{
// If $y is scalar, add it directly to the temporary array
$temp[] = $y;
}
else
{
// If $y is an array, iterate through its key-value pairs and add values to the temporary array
foreach ($y as $k => $v)
{
$temp[] = $v;
}
}
// Return the temporary array
return $temp;
}
// Output HTML preformatted text
echo '<pre>';
// Use array_map to apply 'merge_arrays_by_index' to corresponding elements of $array2 and $array1
print_r(array_map('merge_arrays_by_index', $array2, $array1));
?>
Output:
<pre>Array ( [0] => Array ( [0] => w3resource [1] => 77 [2] => 87 ) [1] => Array ( [0] => com [1] => 23 [2] => 45 ) )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to merge two two-dimensional arrays by interleaving their elements based on index.
- Write a PHP function that takes two arrays of equal length, merges them by alternation, and returns a nested array.
- Write a PHP program to combine two arrays element-wise and store the result as sub-arrays within a larger array.
- Write a PHP script to merge two arrays where one contains keys and the other contains values, then output the combined result as a multidimensional array.
Go to:
PREV : Bead-Sort Algorithm for Array Sorting.
NEXT : Change Array Values to Lower and Upper Case.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.