Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a combination array which contains maximum length?

I have these three arrays:

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

And this is expected result:

/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )

Here is my solution which doesn't work as expected:

print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )

How can I do that?

like image 291
stack Avatar asked Jul 05 '17 04:07

stack


2 Answers

Use this:

array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);

this will merge the arrays into one, then removes all duplicates

Tested Here

It outputs:

Array
(
    [0] => one
    [1] => two
    [2] => three
    [4] => four
    [6] => five
    [7] => six
    [8] => seven
)
like image 94
Derek Avatar answered Nov 15 '22 03:11

Derek


I think this will work just fine

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;

Output is

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
    [5] => six
    [6] => seven
)
like image 27
Praveen Kumar Avatar answered Nov 15 '22 03:11

Praveen Kumar