shuffle multiple string values using PHP

2019-03-06 20:50发布

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.

2条回答
爷、活的狠高调
2楼-- · 2019-03-06 20:55

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
)
查看更多
Deceive 欺骗
3楼-- · 2019-03-06 21:10

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];
查看更多
登录 后发表回答