I have a string stored in my table. It's a number of values separated by pipe:
val 1|val2|val 44
I also have another string, separated by semi-colons that I would like to merge unique values from into the first sting.
abcd; efg; hijklmnop3; val2
So I thought that the easiest way would be to convert them into arrays, merge and keep unique and the implode back into the string.
(my loop) {
$arr1 = array();
$arr2 = array();
$arr1[] = explode(';', $str1);
$arr2[] = explode('|', $str2);
$arr3 = implode("|",array_unique(array_merge($arr1,$arr2)));
}
But when I try to
echo $arr3;
I get
Warning: Array to string conversion
What am I missing here?
CodePudding user response:
Just simplify to following:
$str1 = 'abcd; efg; hijklmnop3; val2';
$str2 = 'val 1|val2|val 44 ';
// explode results an array
$arr1 = array_map('trim', explode(';', $str1));
$arr2 = array_map('trim', explode('|', $str2));
// Implode results a string
$string = implode("|", array_unique(array_merge($arr1, $arr2)));
echo $string;
Results in
abcd|efg|hijklmnop3|val2|val 1|val 44
Note, that explode already returns an array. With the following you add an array to an array, but you just want the array.
$arr1[] = explode(';', $str1);
is the same as array_push($arr1, explode(';', $str1));
The unique of your question failed, because you need to trim the spaces.
'val2' !== ' val2' <-- see the space