The Little Guy Posted June 25, 2010 Share Posted June 25, 2010 I am trying to get a random number between 20 and 50, or between -20 and -50. This is how I am doing it, is there an easier way to do it? // Create a random swirl $arr1 = range(20, 50); $arr2 = range(-50, -20); $arr3 = array_merge($arr1, $arr2); $swirl = $arr3[array_rand($arr3)]; Quote Link to comment Share on other sites More sharing options...
Andy-H Posted June 25, 2010 Share Posted June 25, 2010 rand ? //Edit, ahh I get you, ignore me haha Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted June 25, 2010 Author Share Posted June 25, 2010 That is only between two number I want between 4 numbers. Quote Link to comment Share on other sites More sharing options...
Andy-H Posted June 25, 2010 Share Posted June 25, 2010 Duno if either are 'better' but they both do the job. $arr = range(-50, 50); $arr = array_filter($arr, create_function('$num', 'if ($num > -20 && $num < 20) return false; return true;')); shuffle($arr); echo $arr[0]; $options['options']['min_range'] = -20; $options['options']['max_range'] = 20; $done = false; do { $rand = mt_rand(-50, 50); if (filter_var($rand, FILTER_VALIDATE_INT, $options) !== false) $done = true; }while (!$done); Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted June 25, 2010 Share Posted June 25, 2010 The OP's first attempt was pretty good. Here's how I would do it: <?php $arr = array_merge(range(-50,-20),range(20,50)); shuffle($arr); $your_rand = $arr[0]; echo $your_rand; ?> Ken Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted June 25, 2010 Author Share Posted June 25, 2010 ken I like your method, it is shorter... I will use that unless someone has a better solution! Thank You! Quote Link to comment Share on other sites More sharing options...
Psycho Posted June 25, 2010 Share Posted June 25, 2010 I've got a solution that takes only two lines $no = rand (1, 62); $no = ($no<32) ? ($no-51) : ($no-12); Quote Link to comment Share on other sites More sharing options...
sw0o0sh Posted June 25, 2010 Share Posted June 25, 2010 Get into the habit of using mt_rand() instead btw Quote Link to comment Share on other sites More sharing options...
Andy-H Posted June 29, 2010 Share Posted June 29, 2010 I've got a solution that takes only two lines $no = rand (1, 62); $no = ($no<32) ? ($no-51) : ($no-12); Nice Quote Link to comment Share on other sites More sharing options...
Psycho Posted June 29, 2010 Share Posted June 29, 2010 One line, using mt_rand(): $no = (mt_rand(0,1)) ? mt_rand(20, 50) : mt_rand(-50, -20); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.