$AllNums = array();
//array is { [0]=> string(1) "2" [1]=> string(1) "1" };
$RandNums = array_rand($AllNums, 1);
// var_dump($RandNums) show - int(0)
$Rand = $AllNums[$RandNums[0]];
but echo 'Rand = '.$Rand
print on display Rand =
.
Tell me please why we can not get $Rand
?
array_rand($AllNums, 1);
returns a value, not an array, so you don't have to add [0]
in $Rand = $AllNums[$RandNums[0]];
$AllNums = range(1, 2);
$RandNums = array_rand($AllNums, 1);
$Rand = $AllNums[$RandNums];
You are using it wrong. Should be:
$AllNums = array('1', '2');
$RandNums = array_rand($AllNums, 1); // this return an int() which can be used as an index
$Rand = $AllNums[$RandNums]; // no need to put `[0]`
echo $Rand;
// Actually no need to explicitly put 1, since its default it 1
Use shuffle
:
$AllNums = array();
shuffle($AllNUms)
$Rand = $AllNums[0];
The manual page of array_rand
specifies that if you are getting only one value with array_rand
, it returns a single value. It only returns an array if you are trying to get more values (using the second parameter)
echo $AllNums[array_rand($AllNums)];
use array_rand() http://php.net/array_rand
you can use mt_rand
$RandNums = mt_rand(0, count($AllNums) - 1);
$Rand = $AllSeets[$RandNums];