Search code examples
phparraysunique

Append dot and counter as suffix for values encountered more than once like R's make.unique function


I need the same functionality of R function make.unique in PHP.

In R:

> dup_array = c("a", "b", "a", "c")
> make.unique(dup_array)
[1] "a"   "b"   "a.1" "c"  

In PHP:

> dup_array = array("a", "b", "a", "c")
> magic_function(dup_array)

What is the magic_function?


Solution

  • Well, there are no in-built functions already for this as yet, however, you can create your own custom function for it.

    Keep track of current frequency of the element using a dictionary(associative array) and then attach the current frequency accordingly.

    <?php
    
    function makeUnique($arr){
        $set = [];
        foreach($arr as $k => $v){
            $set[ $v ] = ($set[ $v ] ?? 0) + 1;
            $arr[ $k ] = $arr[ $k ] . ($set[ $v ] > 1 ? '.' .($set[ $v ] - 1) : '');
        }
        return $arr;
    }
    
    print_r(makeUnique($arr));
    

    Online Demo