Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine two arrays without repeating values?

Tags:

arrays

php

I have two arrays:

array('1','2','3','4');
array('4','5','6','7');

Based on them, I'd like to generate an array that contains only unique values:

array('1','2','3','4','5','6','7');

Is there any suitable function for this in PHP?

like image 886
Awan Avatar asked Apr 16 '11 11:04

Awan


People also ask

How do you prevent duplicates in an array?

To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.

How do you unify two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I combine two arrays from another array?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.


1 Answers

You can use array_merge for this and then array_unique to remove duplicate entries.

$a = array('1','2','3','4');
$b = array('4','5','6','7');

$c = array_merge($a,$b);

var_dump(array_unique($c));

Will result in this:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [5]=>
  string(1) "5"
  [6]=>
  string(1) "6"
  [7]=>
  string(1) "7"
}
like image 78
halfdan Avatar answered Oct 07 '22 01:10

halfdan