1

I'm trying to copy 5 random values from one array to another with the following code. The problem is 3 or 4 values get copied and 1 or 2 are always copied as null. I'm not sure what the problem in my code is.

if (count($potential_matches_in_area) >= 5) {
  for ($x = 0; $x < 5; $x++) {

  $index = mt_rand(0, count($potential_matches_in_area) - 1);
  $new_matches[$x] = $potential_matches_in_area[$index];
  unset($potential_matches_in_area[$index]);

  } 

1 Answer 1

1

The problem is, this line:

mt_rand(0, count($potential_matches_in_area) - 1);

You can get duplicate keys, the first time it runs, it runs okay, but once the unset key reappears again, you'll get an undefined index. Why not just use array_rand instead.

if (count($potential_matches_in_area) >= 5) {
    for ($x = 0; $x < 5; $x++) {
        $index = array_rand($potential_matches_in_area);
        $new_matches[$x] = $potential_matches_in_area[$index];
        unset($potential_matches_in_area[$index]);
    } 
}

You'll only get the present keys thats still available.

Sign up to request clarification or add additional context in comments.

2 Comments

I've read that array_rand is less efficient and has some issues with the distribution producing weird results occasionally, however if it is the only way, I will use it
@mankee if you want to insist your mt_rand, you'll need to roll up your own custom function that utilizes mt_rand and then corresponds to your array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.