Search code examples
phparraysobjectunique

PHP create unique value compared to values from object


I need to create a unique value for $total, to be different from all other values from received object. It should compare total with order_amount from object, and then if it is the same, it should increase its value by 0.00000001, and then check again through that object to see if it matches again with another order_amount. The end result should be a unique value, with minimal increase compared to the starting $total value. All values are set to have 8 decmal places.

I have tried with the following but it won't get me the result i need. What am i doing wrong?

function unique_amount($amount, $rate) {

    $total = round($amount / $rate, 8);
    $other_amounts = some object...;

    foreach($other_amounts as $amount) {
        if ($amount->order_amount == $total) {
            $total = $total + 0.00000001;
        }
    }

    return $total;
}

Solution

  • <?php
    
    define('EPSILON',0.00000001);
    $total = 4.00000000;
    $other_amounts = [4.00000001,4.00000000,4.00000002];
    
    sort($other_amounts);
    
    foreach($other_amounts as $each_amount){
        if($total === $each_amount){ // $total === $each_amount->order_amount , incase of objects
            $total += EPSILON;
        }
    }
    
    var_dump($total);
    

    OUTPUT

    float(4.00000003)
    

    You may add an additional break if $total < $each_amount to make it a bit more efficient.

    UPDATE

    To sort objects in $other_amounts based on amount, you can use usort.

    usort($other_amounts,function($o1,$o2){
        if($o1->order_amount < $o2->order_amount ) return -1;
        else if($o1->order_amount > $o2->order_amount ) return 1;
        return 0;
    });