I need to generate an array containing 20 random numbers between 1 and 200. Is there a shorter/cleaner code I can use?
<?php
$x= array (rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200));
echo '<pre>'; print_r($x); echo '</pre>';
?>
<?php
$arr = array();
for($i=0; $i<20; $i++){
$random_num = rand(1,200);
array_push($arr, $random_num);
}
?>
No loops needed.
Use range to create all numbers between 1-200, shuffle it and grab the first 20 items in the array with array_slice.
$range = range(1,200);
shuffle($range);
$random = array_slice($range,0,20);
var_dump($random);