Azem Hajdari Azem Hajdari - 6 months ago 53
PHP Question

PHP Warning: array_rand() expects parameter 1 to be array, boolean given

My code:

$input = array("1", "2", "3", "4", "5", "6", "8", "15", "22");
$value1=$input[array_rand($input)];


I want to randomize given numbers and get just one numbers of them back to "$input", but I got an error :
"PHP Warning: array_rand() expects parameter 1 to be array, boolean given in...

Line where this error is triggered is here:

$value1=$input[array_rand($input)];


How to fix that error ?

?

Thanks!

Answer

This should work:

$input = ["1", "2", "3", "4", "5", "6", "8", "15", "22"];

$randomInputIndex = rand(0, count($input)); // Returns any integer between 0 and 8 in your case
$randomInputValue = $input[$randomInputIndex];
// $input[0] returns 1
// $input[1] returns 2
// $input[7] returns 15
// $input[8] returns 22

Or simply use:

$input = ["1", "2", "3", "4", "5", "6", "8", "15", "22"];

$randomInputValue = array_rand($input);

Read more about PHP's arrays here.

Comments