4

I have a php array that's made up of random numbers from 0-100.

I'm trying to figure out the cleanest and simplest method of picking a random key from that array that is greater than zero. Ultimately I'm looping through the array, subtracting a value from random keys each loop

Pseudo code:

$num_array = array(100,50,60,40,0,30,0,20);

for ($x = 0; $x < 100; $x++) {
    $rnd = RANDOM $num_array KEY WHERE > 0  
    $num_array[$rnd] = $num_array[$rnd] - 10;
}

Any suggestions on how to handle this?

EDIT: Once the loop is over I still want my array to contain 0's (originals, and any new ones after subtraction), and all the key positions need to be intact as before

1
  • Why not filter the zeroes out of the array before picking a random one? Commented Jul 22, 2017 at 11:35

3 Answers 3

2

1st : simple apply array_filter it will filter zeros from array

2nd : Apply array_rand function

<?php

$nums = [70, 100, 40, 30, 0, 45, 10];

$new_nums = array_filter($nums);

$key = array_rand($new_nums , 1);

echo $new_nums [$key];

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

2 Comments

Thanks, once the loop is over I still want my array to contain 0's and all the key positions intact as original, will this do that?
if you want keep the original array means just change the varibale name . check my updated answer . @user1022585
1

I would suggest to first remove the zeroes, and only then pick a random value:

$nums = [70, 100, 40, 30, 0, 45, 10];
$temp = array_values(array_filter($nums));
$random = $temp[mt_rand(0, count($temp) - 1)];

NB: random value is selected according to user comment on the PHP documentation page.

Comments

0

First you need to build an array which doesn't contain zeroes.

pos_nums=array();
 foreach ($nums as $num) {
  if ($num > 0) $pos_nums[] = $num;
}

PHP has the array_rand function documented here.

If you call

$pos_rand_keys = array_rand($pos_nums, 1);

then $pos_rand_keys[0] will be a random value.

2 Comments

wouldn't it be easier to put the array_rand into a loop and break if not 0?
If you have to "keep trying" to pick a random value, the randomness is reduced. It's better to preprocess the array so you have a good data set, then make a random choice once.

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.