Split two delimited strings into arrays of words, merge, then remove duplicates [duplicate]

StackOverflow https://stackoverflow.com/questions/20929752

  •  24-09-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

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; 

OTHER TIPS

$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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top