Search code examples
phparraysfilteringuniquedelimited

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


Array
(
[0] => Array
    (
        [0] => abc@test.com
        [1] => qwrt@sometest.com
        [2] => haritha@elitesin.com
    )

[1] => Array
    (
        [0] => Kanishka.Kumarasiri@elitesin.com
        [1] => Haritha@elitesin.com
    )

[2] => Array
    (
        [0] => Kanishka.Kumarasiri@elitesin.com
        [1] => test@elitesin.com
    )

)

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] => abc@test.com
        [1] => qwrt@sometest.com
        [2] => haritha@elitesin.com
        [3] => Kanishka.Kumarasiri@elitesin.com
        [4] => test@elitesin.com
    )

  )

Solution

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

    <?php
    $arr = [
        ["abc@test.com", "qwrt@sometest.com", "haritha@elitesin.com"],
        ["Kanishka.Kumarasiri@elitesin.com,Haritha@elitesin.com"],
        ["Kanishka.Kumarasiri@elitesin.com,test@elitesin.com"]
    ];
    $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));
    
    ?>