PHP Select a random line of two lines

$apple=""; $banana=""; $apple="Red"; $banana="Blue"; $random(rand($apple, $banana); echo $random; 

How can I select a random string (quickly) through PHP?

+6
source share
6 answers

Code issue

The PHP rand() function takes two numbers as input to form a range for choosing a random number. You cannot feed the lines.

See the PHP man page for rand() .

Decision

You can use array_rand() :

 $strings = array( 'Red', 'Blue', ); $key = array_rand($strings); echo $strings[$key]; 

Another option is to use shuffle() .

 $strings = array( 'Red', 'Blue', ); shuffle($strings); echo reset($strings); 
+17
source

What about:

 $random = rand(0, 1) ? 'Red' : 'Blue'; 
+13
source

Use an array:

 $input = array("Red", "Blue", "Green"); echo $input[array_rand($input)]; 
+5
source

array_rand() is the best way:

 $varNames = array('apple','banana'); $var = array_rand($varNames); echo ${$varNames[$var]}; 
+2
source

The rand() function has two parameters: the lower limit for a random number and the upper limit. You cannot use such variables because this is not how the function works.

Take a look at the documentation:
http://php.net/rand

A simple way to achieve what you want:

 $array = array(); $array[0] = 'banana'; $array[1] = 'orange'; $randomSelected = $array[rand(0,(count($array)-1))]; 

As far as I read, this solution is faster than array_rand() . I see if I can find the source of this.

+1
source

Go to this old question, which tops Google results. You can have more than two options and still get everything on one line.

 echo ['green', 'blue', 'red'][rand(0,2)]; 
0
source

Source: https://habr.com/ru/post/905189/


All Articles