Difference between array_merge() and array_combine() in PHP

array_merge()

Syntax : array_merge(array1, array2...): array

The array_merge() function merges the elements of one or more arrays into a single resultant array in such a way, So that the values of one array append to the end of previous ones. We can pass one or more arrays as parameters.

Example :

<?php
  $array1 = array(1, 'a' => "white", 10, 'b' => "apple");
  $array2 = array('a' => "red", 2, 'xyz', 4, 'b' => "apple");
  $result = array_merge($array1, $array2);
  print_r($result);
?>

Output :

Array ( [0] => 1 [a] => red [1] => 10 [b] => apple [2] => 2 [3] => xyz [4] => 4 )

Note :

  • If the arrays have same string keys, then the value of last array for that key will overwrite the value of previous ones.
  • If the arrays contain numeric keys, then the values of last array will not overwrite the values of previous arrays and will be append on last of the resultant array.
  • If there is only one array with numeric keys, Then the key of resultant array will be re-indexed and start from 0.

array_combine

Syntax : array_combine(array $keys, array $values): array

The array_combine() function creates an array by using the elements from one “keys” array and one “values” array.

While passing two arrays in the function, make sure the number of elements in both the arrays are equal, otherwise it will return an error.

Example :

<?php
  $name=array("Ikhlaque Ahmed","Raheel","Subhan");
  $age=array("35","29","10");

  $combine_array = array_combine($name,$age);
  print_r($combine_array);
?>

Output :

Array ( [Ikhlaque Ahmed] => 35 [Raheel] => 37 [Subhan] => 43 )

Conclusion

We learn today array_merge vs array_combine. This is most asking question on PHP interview. This article will help you to understand better about differences between array_merge vs array_combine.

Developer Diary

Share
Published by
Developer Diary

Recent Posts

Laravel vs Node Js: Which One Is Good For What?

Introduction In the world of web development, selecting the correct framework is critical. Laravel and…

3 months ago

Docker Cheatsheet: Essential Commands and Explanations

Introduction By enabling containerization, Docker has transformed the way software is built, deployed, and managed.…

8 months ago

Difference between Memcached and REDIS – Secrets of Caching

Introduction Speed and efficiency are critical in the ever-changing world of web development. Effective caching…

8 months ago

How to Revert a Git Commit: A Simple Example

Introduction Git, a popular version control system in software development, enables developers to track changes,…

8 months ago

What is Git Stash and Why Do You Need It

Introduction Are you tired of grappling with tangled changes and unfinished work while using Git?…

8 months ago

Difference between git stash pop and git stash apply

Introduction Version control is essential in software development because it ensures that changes to a…

8 months ago