2

I have a variable called

  $core

I also have 3 other variables called

 $one, $two, $three

I need to (many times) display a random combination of these where $core is always included and 1 of the 3 other variables are included once either before or after:

eg:

 $two $core
 $core $one
 $three $core
 $core $two

I'm unsure how to get this randomness working with PHP? A push in the right direction would be greatly appreciated.

thx

1
  • Do they have to be named that? You could create a function that returns an array containing those values in a random order, except for the $core value being index 0. Commented Jan 2, 2012 at 20:38

3 Answers 3

4

Don't use individual variables. Use an array:

$vals = array($one, $two, $three);

build a temporary array:

$new = array($core, $vals[array_rand($vals, 1)]);

and then shuffle it:

shuffle($new);
Sign up to request clarification or add additional context in comments.

1 Comment

This wont randomize whether $core comes before or after the value printed. edit oh wait, misread
1

Hold the three variables in an array. Then call rand() between 0 and 1 to determine whether an array value or $core should be printed first. At the same time, call a random value from the array

// Array of the three vars
$arr = ($one, $two, $three);
// If 0 is chosen, print an array value then $core. 
// Otherwise print $core than an array value
echo rand(0, 1) == 0 ? $arr[rand(0,2)] . " " . $core : $core . " " . $arr[rand(0,2)];

Comments

0

Perhaps store all 4 values in an array. Randomly select an item. Remove it. If the value isn't $core, randomly select again from the shorter array.

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.