Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Select a Random String from Two Strings

Tags:

php

random

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

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

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

like image 235
TheBlackBenzKid Avatar asked Jan 05 '12 12:01

TheBlackBenzKid


2 Answers

What about:

$random = rand(0, 1) ? 'Red' : 'Blue';
like image 145
Razvan Grigore Avatar answered Sep 27 '22 21:09

Razvan Grigore


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);
like image 24
Treffynnon Avatar answered Sep 27 '22 19:09

Treffynnon