Search code examples
phparraysfilteringuniquedelimited

Collect unique values from a 1d array of comma-separated values


Array
(
[0] => Array
    (
        [0] => [email protected]
        [1] => [email protected]
        [2] => [email protected]
    )

[1] => Array
    (
        [0] => [email protected]
        [1] => [email protected]
    )

[2] => Array
    (
        [0] => [email protected]
        [1] => [email protected]
    )

)

I have an array like this and I want to get unique values from this array.

But my code is failing

for ($i = 0; $i < count($return_arr); $i++) {

$new_value[] = explode(",", $return_arr[$i]);
}

print_r (array_unique($new_value));

It says array to string conversion error

i want the array to be like this get only the unique email ids

 Array
(
[0] => Array
    (
        [0] => [email protected]
        [1] => [email protected]
        [2] => [email protected]
        [3] => [email protected]
        [4] => [email protected]
    )

  )

Solution

  • Because your code is wrong, you are trying to explode something which is not contained in your array, try this code:

    <?php
    $arr = [
        ["[email protected]", "[email protected]", "[email protected]"],
        ["[email protected],[email protected]"],
        ["[email protected],[email protected]"]
    ];
    $allEmails = array();
    foreach($arr as $array){
        foreach($array as $email){
            $allEmails[] = explode(",",$email);
        }
    }
    $new_value = array();    
    foreach($allEmails as $array){
        foreach($array as $email){
            $new_value[] = strtolower($email);
        }
    }
    
    print_r (array_unique($new_value));
    
    ?>