0

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!

14
  • 2
    ..because $inputis of type boolean, not an array. RTM Commented May 28, 2016 at 23:58
  • since we don't know what $input is, or where it comes from, we can't really help. Fact is, $input is not an array. Commented May 28, 2016 at 23:59
  • @Jeff Oh, that's great, thanks very much for that information, so what to do to not read this error on my server over and over again ? Commented May 28, 2016 at 23:59
  • Are you serious? Did you even read the error message? It could not be any clearer. Commented May 29, 2016 at 0:00
  • @Sverri M. Olsen I am sorry, but I have no idea what to do to fix that. Commented May 29, 2016 at 0:01

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I am think that something is like that, because if I remember correctly same types of "boolean" error I am getting when I edited my code from "mysql" to "mysqli"... I am sure that will work! Many thanks JasonK !
I need $input to be just 1 given RANDOM number from those : "1", "2", "3", "4", "5", "6", "8", "15", "22"
Both examples should do exactly that... have you tried them out already?
that second version will work for me I guess, There is not needed to count, but important is just to give me back randomly one number from those numbers given: "1", "2", "3", "4", "5", "6", "8", "15", "22" etc. Thank you so much mr. JasonK!
No problem, please accept the answer if it solved your problem. Good luck.
|
1

Just the way you need it!

$input = array("preto", "vermelho", "laranja", "roxo", "abacate", "pera", "uva");


$random = array_rand($input, 1);
print_r($input[$random]);

Result random unique:

laranja

Comments

0
$value1= $input->random(number);

ps: number = number of element you want to get ,

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.