Search code examples
phpunique-array

php: array_unique missing a duplicate


I have been struggling with a minor issue with the array_unique for a couple of days now.

Somehow the output always leaves the last duplicate in the array.

I am getting the text from a text box in an html form

$IDs = trim($_POST['IDs']);
$IDs = explode("\n", $IDs);
$IDs = array_filter($IDs, 'trim');
$ID = array_unique($IDs,0);
print_r($ID);

sample input:

012345 0123456 01234567 012345 0123456 01234567 012345 0123456 01234567 sample output:

Array ( [0] => 012345 [1] => 0123456 [2] => 01234567 [3] => 01234567 )

sample input:

012345 0123456 01234567 012345 0123456 01234567 012345 0123456 sample output:

Array ( [0] => 012345 [1] => 0123456 [2] => 01234567 [3] => 0123456 ) 

not sure why the last duplicate keeps getting missed.

Am sure I am missing something but cannot seem to figure it out.

Added the foreach loop hoping to fix it but even with that I keep getting the same result.


Solution

  • You should use array_map instead of array_filter.

    Like:

    $IDs = trim($_POST['IDs']);
    $IDs = explode("\n", $IDs);
    $IDs = array_map('trim', $IDs);
    $ID = array_unique($IDs,0);
    print_r($ID);