1
$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?

6 Answers 6

3

Use shuffle:

$AllNums = array();
shuffle($AllNUms)
$Rand = $AllNums[0];
Sign up to request clarification or add additional context in comments.

2 Comments

This is my preferred method
Always important to mention that it will completely change the array though.
1

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

Comments

1

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

Comments

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)

Comments

0

echo $AllNums[array_rand($AllNums)];

use array_rand() http://php.net/array_rand

Comments

0

you can use mt_rand

$RandNums = mt_rand(0, count($AllNums) - 1);
$Rand = $AllSeets[$RandNums];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.