hemanth kumar
hemanth kumar

Reputation: 537

Remove duplicate substring from comma seperated string in php

I have this string: $entitlemnet = '43857403,erot,43857403,erot,rejh'

I want to remove all the duplicate values from this string. How can i do that?

See code below.

$roql_Ent_result = RNCPHP\ROQL::query($EntQuery)->next();

while ($Ent_result = $roql_Ent_result->next())
{
    $Entitlement = $Ent_result['Entitlement'];
    $findme = $Entitlement.",";
    $pos = stripos($EntitlementString, $findme);

    if ($pos === false)
    {
        $EntitlementString = $EntitlementString.$Entitlement.", "; 
    }
}

if ($EntitlementString != "")
{
    $EntitlementString = substr($EntitlementString,0,(strlen($EntitlementString)-2)).";";
}

Upvotes: 2

Views: 669

Answers (3)

Hemanth Nagendrappa
Hemanth Nagendrappa

Reputation: 74

Try this

$entitlemnet = "43857403,erot,43857403,erot,rejh";
$result = implode(',', array_unique(explode(',', $entitlemnet)));
echo $result;

Upvotes: 1

JazzCat
JazzCat

Reputation: 4583

If you simply want to remove the duplicates from the string.

$entitlemnet = '43857403,erot,43857403,erot,rejh';
$unique_string = implode(',', array_unique(explode(',', $entitlemnet)));
  1. Turn your string into an array by splitting it with explode() by delimiter ','

  2. Remove duplicate values with the function array_unique()

  3. Turn the array back into a string by concatenating the array values with delimiter ','

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163632

I think you can do it like this:

$entitlemnet = "43857403,erot,43857403,erot,rejh";
$result = implode(',', array_unique(explode(',', $entitlemnet)));
echo $result;

Will result in:

43857403,erot,rejh

Upvotes: 0

Related Questions