Felipe Alarcon
Felipe Alarcon

Reputation: 956

How to replace a value in array by another different value in PHP?

I'm trying to find a way to replace any duplicated value but the only solution I have found so far is array_unique which doesn't really work for me as I need the duplicate to be replaced by another number which itself is not a duplicate.

 function generate_random_numbers($rows, $delimiter)
 {
     $numbers = array();

     for($i = 0; $i < $delimiter; $i++)
     {
         $numbers[$i] = rand(1, $rows);

         if(in_array($i, $numbers))
         {
            $numbers[$i] = rand(1, $row);
         }
     }
     return $numbers;
 }

 $numbers = generate_random_numbers(20, 10);

 print_r($numbers);

would anyone help me out on this one please?

Upvotes: 0

Views: 49

Answers (3)

Rizier123
Rizier123

Reputation: 59681

You can do this way easier and faster.

Just create an array for all possible numbers with range(). Then shuffle() the array and take an array_slice() as big as you want.

<?php

    function generate_random_numbers($max, $amount) {
        if($amount > $max)
            return [];

        $numbers = range(1, $max);
        shuffle($numbers);
        return array_slice($numbers, 0, $amount);
    }

    $numbers = generate_random_numbers(20, 10);
    print_r($numbers);

?>

And if you want to get 490 unique elements from a range from 1 - 500, 10'000 times:

  • My version: ~ 0.7 secs
  • Your version: Order 2 birthday cakes, you will need them.

Upvotes: 4

WhoIsJohnDoe
WhoIsJohnDoe

Reputation: 338

You were pretty close. The if-clause needs to be a loop, to get new random number.
(Also your in_array was slightly wrong)

function generate_random_numbers($rows, $delimiter) {
    $numbers = array();

    for($i = 0; $i < $delimiter; $i++) {
        do {
            $number = rand(1, $rows);
        }
        while(in_array($number, $numbers));

        $numbers[] = $number;
    }

    return $numbers;
 }

Upvotes: 1

kainaw
kainaw

Reputation: 4334

You are inserting a random number and then, if it is already in the array (which it MUST be because you just inserted it), you use a new random number, which might be a duplicate. So, you have to get a number that is not a duplicate:

do {
    $num = rand(1,$rows);
} while(!in_array($num, $numbers));

Now, you know that $num is not in $numbers, so you can insert it:

$numbers[] = $num;

Upvotes: 1

Related Questions