3

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Alforreca
  • 35
  • 4
  • 1
    Where's the closing parenthesis for `implode()`? – Pang Jan 05 '14 at 03:40
  • 2
    Your array only contains the two unique elements... maybe you are looking for an array of unique words... in that case the two strings need to be exploded by whitespace characters then merged together prior to the array unique call. – Orangepill Jan 05 '14 at 03:50
  • Edited, with result and typo ) fixed – Alforreca Jan 05 '14 at 03:50
  • Orangespill something like $a_string = explode("\n", $a); $b_string = explode("\n", $b); $a_b_array = array($a_string, $b_string); – Alforreca Jan 05 '14 at 03:53

2 Answers2

5

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; 
Orangepill
  • 24,500
  • 3
  • 42
  • 63
1
$a = 'mysql string 1'; // basically words A, B, C
$b = 'mysql string 2'; // basically words D, A, E

$a_explode = explode(" ", $a);
$b_explode = explode(" ", $b);

$a_b_array =  array_unique(array_merge($a_explode, $b_explode));
sort($a_b_array);
var_dump($a_b_array);
echo implode(", ", $a_b_array);

Output :

array (size=4)
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string 'mysql' (length=5)
  3 => string 'string' (length=6)
1, 2, mysql, string
siddharth
  • 231
  • 1
  • 4
  • 14