0

I have an array-like:

Array
(
    [0] => 4
    [1] => 1861
)
Array
(
    [0] => 4
    [1] => 1938
)
Array
(
    [0] => 4
    [1] => 1452
)
Array
(
    [0] => 4
    [1] => 1938
)
Array
(
    [0] => 21
)

This is a single array contain this array of elements. I need the result like :

$arr = array(4,1861,1938,1452,21);

That means I need the only array unique values from these arrays. For this, I am using array_walk_recursive(), array_merge() etc. But I didn't get my results.

2 Answers2

2

Merge all the arrays and then call array_unique().

$result = array_unique(array_merge(...$array));

...$array spreads the elements of the original array into arguments to array_merge().

If you're using an old version of PHP before ellipsis, use call_user_func_array() instead.

$result = array_unique(call_user_func_array('array_merge', $array));
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I am using the PHP 5.4 version. Is there any option with this version? –  Jul 29 '21 at 16:13
  • Use `call_user_func_array('array_merge', $array)` instead of using ellipsis. – Barmar Jul 29 '21 at 16:14
  • I already tried this function.But I dint get the result. –  Jul 29 '21 at 16:15
  • Is there any problem with call_user_func_array in PHP 5.4 version? because I tried and found there is no result. And I just display my array values, I got my array values. After that, I used this function I dint get any results? –  Jul 29 '21 at 17:49
  • I just tried it in PHP 5.4 and it worked fine. – Barmar Jul 29 '21 at 17:51
  • `$array = [[4, 1861], [4, 1938], [4, 1452], [4, 1938], [21]]; $result = array_unique(call_user_func_array('array_merge', $array)); print_r($result);` – Barmar Jul 29 '21 at 17:51
0

you need to use array_merge then array_unique

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

check this please https://stackoverflow.com/a/10572576/2429434

Mhd Wael Jazmati
  • 636
  • 9
  • 18
  • I have only one array. $array1. In array 1 contains different arrays with values. –  Jul 29 '21 at 15:55
  • They said the input is a single array, not multiple variables. – Barmar Jul 29 '21 at 15:55
  • @Sonia in this case you use this `$array = array_unique (array_merge (...$array1)); ` check this https://stackoverflow.com/a/17041344/2429434 – Mhd Wael Jazmati Jul 29 '21 at 15:59
  • I understood this method and I tried to this one, but my execution stops after this code –  Jul 29 '21 at 16:00