1

I have this phrases ex: test 1, test 2, test 3, now how to show on load page in random mode?

ex function

function random()
{
    $array = ['test 1', 'test 2', 'test 3'];

    return $random_array;
}
Amir Hassan Azimi
  • 9,180
  • 5
  • 32
  • 43
Federal09
  • 639
  • 4
  • 9
  • 25

5 Answers5

4

Put them in an array and use array_rand to get a random key.

function random()
{
  $phrases = array(
    'random test 1',
    'random test 2',
    'random test 3'
  );

  return $phrases[array_rand($phrases)];
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
3

Put them in an array and pick a random element:

$array = array();
$array[] = 'test1';
$array[] = 'test2';
$array[] = 'test3';
$array[] = 'test4';

echo $array[ mt_rand( 0 , (count( $array ) -1) ) ];

Or you could just shuffle the array and pick the first element:

shuffle( $array );

echo $array[0];

OR, another method I've just discovered:

Use array_rand(); See some of the other answers.

1
<?php

function random(){
    $phrases = array(
        "test1",
        "test2",
        "test3",
        "test4"
        );

    return $phrases[mt_rand(0, count($phrases)-1)]; //subtract 1 from total count of phrases as first elements key is 0
}

echo random();

and a working example here - http://codepad.viper-7.com/scYVLX

edit Use array_rand() as suggested by Arnold Daniels

Pankucins
  • 1,690
  • 1
  • 16
  • 25
1

The best and shortest solution in php is this:

$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[array_rand($array)];

Update: for above answers in as PHP 7.1 is to use random_int function instead of mt_rand since it's faster:

$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[random_int(0, (count($array) - 1))];

For more information about mt_rand v.s random_int see the link below: https://stackoverflow.com/a/28760905/2891689

Amir Hassan Azimi
  • 9,180
  • 5
  • 32
  • 43
-1

Put them in an array and return a random value.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592