skip to Main Content

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?

2

Answers


  1. You could do it like this:

    <?php
    function make_unique($a) {
        $d = array_count_values($a);
        $f = array_filter($d, function($k){
            return $k>1;
        });
        $k = array_keys($f);
        for ($i=0; $i < count($a); $i++) { 
            if(in_array($a[$i],$k) && $d[$a[$i]]>0) {
                $f[$a[$i]]--;
                $n = $d[$a[$i]]-$f[$a[$i]];
                if($n>1)$a[$i] = $a[$i].".".($n-1);
            }
        }
        return $a;
    }
    

    You can test it:

    $a = ["a","d","c","b","a","b","a","a","d","d","a"];
    print_r(make_unique($a));
    

    And results in:

    Array
    (
        [0] => a
        [1] => d
        [2] => c
        [3] => b
        [4] => a.1
        [5] => b.1
        [6] => a.2
        [7] => a.3
        [8] => d.1
        [9] => d.2
        [10] => a.4
    )
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search