Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array - search for random key where value is over 0

Tags:

arrays

php

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

like image 282
user1022585 Avatar asked Oct 20 '25 16:10

user1022585


2 Answers

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];

?>
like image 127
JYoThI Avatar answered Oct 23 '25 05:10

JYoThI


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.

like image 32
trincot Avatar answered Oct 23 '25 07:10

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!