TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

PHP Select a Random String from Two Strings

$apple="";
$banana="";
$apple="Red";
$banana="Blue";

$random(rand($apple, $banana);
echo $random;

How can I select a random string (fast) via PHP?

Upvotes: 18

Views: 31373

Answers (6)

Pete_1
Pete_1

Reputation: 1011

Ran into this old question that tops google's results. You can have more than two options and still get it all on one line.

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

Upvotes: 6

Razvan Grigore
Razvan Grigore

Reputation: 1898

What about:

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

Upvotes: 42

OptimusCrime
OptimusCrime

Reputation: 14863

The function rand() has two parameters: a lower-limit for a random number and an upper limit. You can not use variables like that because it is not the way the function works.

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

A simple way to achieve what you want is this:

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

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

Upvotes: 2

Treffynnon
Treffynnon

Reputation: 21553

Issue with your code

The PHP rand() function takes two numbers as input to form the range to pick a random number from. You cannot feed it strings.

See the PHP manual page for rand().

Solutions

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

Upvotes: 32

Manse
Manse

Reputation: 38147

Use an array :

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

Upvotes: 13

DaveRandom
DaveRandom

Reputation: 88647

array_rand() is probably the best way:

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

Upvotes: 3

Related Questions