0

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?

0

3 Answers 3

2

Make a plain array from input

$res = array();
foreach ($array  as $item)
  $res = array_merge($res, explode(', ', $item)); 

and then use array_unique($res)

Sign up to request clarification or add additional context in comments.

Comments

2
$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
)

2 Comments

@user2413654. Ok. Splash58's code less, because he not trim values.
It is not necessary for splash58 to trim the values, because explode() is (properly) splitting on all comma-space instances.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.