Find and replace duplicates in Array

后端 未结 4 1114
小蘑菇
小蘑菇 2021-01-13 20:14

I need to make app with will fill array with some random values, but if in array are duplicates my app not working correctly. So I need to write script code which will find

4条回答
  •  温柔的废话
    2021-01-13 20:42

    You can just keep track of the words that you've seen so far and replace as you go.

    // words we've seen so far
    $words_so_far = array();
    // for each word, check if we've encountered it so far
    //    - if not, add it to our list
    //    - if yes, replace it
    foreach($charset as $k => $word){
        if(in_array($word, $words_so_far)){
            $charset[$k] = $your_replacement_here;
        }
        else {
            $words_so_far[] = $word;
        }
    }
    

    For a somewhat-optimized solution (for cases where there are not that many duplicates), use array_count_values() (reference here) to count the number of times it shows up.

    // counts the number of words
    $word_count = array_count_values($charset);
    // words we've seen so far
    $words_so_far = array();
    // for each word, check if we've encountered it so far
    //    - if not, add it to our list
    //    - if yes, replace it
    foreach($charset as $k => $word){
        if($word_count[$word] > 1 && in_array($word, $words_so_far)){
            $charset[$k] = $your_replacement_here;
        }
        elseif($word_count[$word] > 1){
            $words_so_far[] = $word;
        }
    }
    

提交回复
热议问题