shuffle multiple string values using PHP

2019-03-06 20:41发布

问题:

Hiii Everyone,

I have 4 options for each question.Each string Is carrying Lengthy sentences.My variables will be like option1,option2,option3,option4.I want to shuffle this variable order like 3,2,1,4 or similarly it will shuffle like random function.I searched in many way Random() function used for numbers and I saw str_shuffle() it will shuffle only one string that two with string collapse.I want just to rearrange strings order .Is this possible with PHP.If its so please help me with Solution.Thanks in advance.

回答1:

Its better to use an array to achieve this.

$options = array(
  'Option One',
  'Option Two',
  'Option Three',
  'Option Four'
); 
//Shuffle the array
shuffle($options);

You can access the options like this (The order will be random);

$options[0];
$options[1];
$options[2];
$options[3];


回答2:

Put variables in an array and then shuffle the array

$answers = array(
        'Answer 1',
        'Answer 2',
        'Answer 3',
        'Answer 4'
    );


shuffle($answers);
print_r($answers);

shuffle($answers);
print_r($answers);

This will output something like:

Array
(
    [0] => Answer 3
    [1] => Answer 1
    [2] => Answer 4
    [3] => Answer 2
)
Array
(
    [0] => Answer 4
    [1] => Answer 2
    [2] => Answer 1
    [3] => Answer 3
)