Wednesday, November 20, 2024
Google search engine
HomeLanguagesPHP array_​merge() Function

PHP array_​merge() Function

The array_merge() function is an inbuilt function in PHP that is used to merge two or more arrays into a single array. This function merges the elements or values of two or more arrays together to make a single array. 

The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that is needed to be merged and returns a new array with merged values of arrays passed in the parameter.

Syntax:

array array_merge(array ...$arrays)

Parameters: This parameter holds the array list that needs to merge to make a single array.

Return Value: This function returns the merged array and returns empty array id parameter array is not given.

Note: In the 7.4.0 version, this function can work without parameters but formerly, at least one parameter is required for this function.

Example 1:

PHP




<?php
  
$arr1 = array(5, 10, 15, 20);
  
$arr2 = array(11, 12, 13, 14);
  
$arr = array_merge($arr1, $arr2);
  
var_dump($arr);
  
?>


Output:

array(8) {
      [0] => int(5)
      [1] => int(10)
      [2] => int(15)
      [3] => int(20)
      [4] => int(11)
      [5] => int(12)
      [6] => int(13)
      [7] => int(14)
}

Example 2:

PHP




<?php
  
$arr1 = array(
    'Geeks'  => "HTML"
    'GFG'  => "CSS"
    'Geek'  => "JavaScript"
    'G4G' => "PHP"
);
  
$arr2 = array(
    'Geeks' => "CPP"
    'G4G' => "Java"
    'Geek' => "Python"
    'neveropen'   => "DSA"
);
  
$arr = array_merge($arr1, $arr2);
  
var_dump($arr);
  
?>


Output:

array(5) {
      ["Geeks"] => string(3) "CPP"
      ["GFG"] => string(3) "CSS"
      ["Geek"] => string(6) "Python"
      ["G4G"] => string(4) "Java"
      ["neveropen"] => string(3) "DSA"
}

Reference: https://www.php.net/manual/en/function.array-merge.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments