I have an array of languages that looks like this: (this data is pulled from mysql stored as: e.g. field value: greek, polish)
Array
(
[0] =>
[1] => french
[2] => french, greek
[3] => german
[4] => greek
[5] => greek, polish
[6] => italian
[7] => spanish
[8] => spanish, italian
[9] => spanish, portuguese
)
I have tried using array_unique($languages) but the output stays the same.
I assume it is because of the comma.
Any idea on how to just have unique values? e.g. one each of: french, greek, german, polish, italian, spanish, and portuguese?
Make a plain array from input
$res = array();
foreach ($array as $item)
$res = array_merge($res, explode(', ', $item));
and then use array_unique($res)
$data = array_map(function ($item) {
// explode values by "," and trim spaces
return array_map('trim', explode(',', $item));
}, $your_data);
// merge all nested arrays from $data and return unique
return array_unique(
call_user_func_array('array_merge', $data);
);
Your result will be:
Array
(
[0] =>
[1] => french
[2] => greek
[3] => german
[4] => polish
[5] => italian
[6] => spanish
[7] => portuguese
)
Possible solution:
function getUniqueSubValues($array) {
$result = [];
foreach($array as $element) {
$result += preg_split('/\s*,\s*/', $element);
}
return array_unique($result);
}
I'm looping over all values inside the array and splitting each of them further into subvalues.
I'm using preg_split('/\s*,\s*/', ...)
instead of explode(',', ...)
because otherwise the space after the ,
would be kept and we would have to trim it.
I'm merging all subvalues into the results array, and at the end I'm returning the unique values of that array.