I'm struggling to remove duplicates words found within two strings.
When I call array_unique
, the duplicated words are not removed.
$a = 'mysql string 1';// basically words A, B, C
$b = 'mysql string 2';// basically words D, A, E
$a_b_array = array($a, $b);
sort($a_b_array);
$a_b_string = implode("\n", array_unique($a_b_array));
echo $a_b_string; //returns $a and $b with duplicated data
Expected result would be: A, B, C, D, E
First of all you are dealing with an array of two elements. You will need to explode each element into arrays first.
<?php
// define your inputs
$a = 'A, B, C';
$b = 'D, A, E';
// explode the string into arrays and merge them
$a_b_array = array_merge(explode(",", $a), explode(",", $b));
// trim off any pesky leading or trailing spaces from the elements
$a_b_array = array_map("trim", $a_b_array);
sort($a_b_array);
// tape the elements back together separated by a newline
$a_b_string = implode("\n", array_unique($a_b_array));
echo $a_b_string;