Joscplan
Joscplan

Reputation: 1034

Remove duplicates inside a for loop in PHP

I have used for to get some data from a string, now I need to remove the duplicates from it.

The code I have is this:

for ($i = 0, $l = count($videos); $i < $l; $i++) {
    $video = explode('>>',$videos[$i]);
    $audio = str_replace(' ','',$video[2]);
    $subs = str_replace(' ','',$video[3]);
    $lang = $audio.'_'.$subs.', ';
}

Which returns this:

es_en, en_es, es_en, es_en, en_es, en_en,

Is there a way to remove the duplicates of it using PHP?

Upvotes: 0

Views: 554

Answers (1)

Lim H.
Lim H.

Reputation: 10050

EDIT: Sorry I was a bit careless

$cache = [];
for ($i = 0, $l = count($videos); $i < $l; $i++) {
    $video = explode('>>',$videos[$i]);
    $audio = str_replace(' ','',$video[2]);
    $subs = str_replace(' ','',$video[3]);
    $lang = $audio.'_'.$subs;
    if (!in_array($lang, $cache)){
        $cache[] = $lang;
    }
}
$result = implode(',', $cache);

Upvotes: 1

Related Questions