Php :: one function to execute array_unique (array_merge ($ a, $ b));

I know that I can use array_unique(array_merge($a,$b));

to merge two arrays and then remove any duplicates,

but

is there an individual function that will do this for me?

(I know that I can write it myself, which simply calls them, but I'm just curious).

+5
source share
5 answers

There is no such function. Programming languages ​​in general give you a certain set of tools (functions), and you can combine them to get the desired results.

In fact, it makes no sense to create a new function for each used case, if this is not a very common use case - and yours, it seems, is not one.

+6

, array_unique(array_merge($a,$b)); - .

.

+5

. - ( )

$array1 = array('abc', 'def');
$array2 = array('zxd', 'asdf');

$newarray = array_unique(array($array1, $array2));

. , , ?

0
source
//usage $arr1=array(0=>"value0", 1=>"value1", 2=>"value2"); $arr2=array(0=>"value3", 1=>"value4", 2=>"value0") => $result=mergeArrays($arr1,$arr2); $result=Array ( [0] => value0 [1] => value1 [2] => value2 [3] => value3 [4] => value4 )

function mergeArrays () {
    $result=array();
    $params=func_get_args();
    if ($params) foreach ($params as $param) {
        foreach ($param as $v) $result[]=$v;
    }
    $result=array_unique($result);
    return $result;
}
0
source

In php 5.6+, you can also use the new argument unpacking to avoid multiple calls to array_merge (which speeds up your code significantly): https://3v4l.org/arFvf

<?php

$array = [
    [1 => 'french', 2 => 'dutch'],
    [1 => 'french', 3 => 'english'],
    [1 => 'dutch'],
    [4 => 'swedish'],
];

var_dump(array_unique(array_merge(...$array)));

Outputs:

array(4) {
  [0]=>
  string(6) "french"
  [1]=>
  string(5) "dutch"
  [3]=>
  string(7) "english"
  [5]=>
  string(7) "swedish"
}
0
source

All Articles