Search code examples
phparraysechoexplodeimplode

Array diff only working with first word in array


using array_diff to filter my array and make sure that if the word is in the filter, it will not be included in the echo. Right now if I replace array2 with "test1, test4" the output will be "test2, test3" which is correct, but instead if I replace array2 with "test2, test4" which should output "test1, test3" I am instead getting an output of "test1, test2, test3" so it is not filtering it out. I know this is probably a very simple fix I am just overlooking it. I will post the code below.

<?php
$array1 = "test1, test2, test3";
$array2 = "test2, test4";

$myArray = explode(',', $array1);
$myArray2 = explode(',', $array2);
$unique=array_diff($myArray, $myArray2);
echo implode(',', $unique); 
?>

Solution

  • You need to use trim with array_map, like below code.

    $array1 = "test1, test2, test3";
    $array2 = "test2, test4";
    
    $myArray = array_map('trim', explode(',', $array1));
    $myArray2 = array_map('trim', explode(',', $array2));
    
    $unique=array_diff($myArray, $myArray2);
    echo implode(',', $unique);