phparraysarray-unique

How can you get unique values from multiple arrays using array_unique?


Is there any way to put two or more arrays into the array_unique() function? If not, is there any other solution to get unique results from multiple arrays?


Solution

  • The answer to the first part of your question is NO.

    The array_unique function definition in the PHP manual states that array_unique takes exactly two arguments, one array, and an optional integer that determines the sorting behavior of the function.

    array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
    

    Rather than take the manual's word for it, here are some test arrays.

    $one_array      = ['thing', 'another_thing', 'same_thing', 'same_thing'];
    $two_arrays     = ['A', 'B', 'C', 'thing', 'same_thing'];
    $or_more_arrays = ['same_thing', 1, 2, 3];
    

    A couple of test show that the function does work as advertised:

    $try_it = array_unique($one_array);
    

    returns ['thing', 'another_thing', 'same_thing'];

    $try_it = array_unique($one_array, $two_arrays);
    

    gives you a warning

    Warning: array_unique() expects parameter 2 to be integer, array given

    and returns null.

    $try_it = array_unique($one_array, $two_arrays, $or_more_arrays);
    

    also gives you a warning

    Warning: array_unique() expects at most 2 parameters, 3 given

    and returns null.


    The answer to the second part of your question is YES.

    To get unique values using array_unique, you do have to have one array of values. You can do this, as u_mulder commented, by using array_merge to combine the various input arrays into one before using array_unique.

    $unique = array_unique(array_merge($one_array, $two_arrays, $or_more_arrays));
    

    returns

    ['thing', 'another_thing', 'same_thing', 'A', 'B', 'C', 1, 2, 3];
    

    If instead of several individual array variables, you have an array of arrays like this:

    $multi_array_example = [
        [1, 2, 3],
        [2, 3, 4], 
        [3, 4, 5],
        [4, 5, 6]
    ];
    

    Then you can unpack the outer array into array merge to flatten it before using array_unique.

    $unique = array_unique(array_merge(...$multi_array_example));
    

    Or in older PHP versions (<5.6) before argument unpacking, you can use array_reduce with array_merge.

    $unique = array_unique(array_reduce($multi_array_example, 'array_merge', []));
    

    returns [1, 2, 3, 4, 5, 6]