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;
}
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;
}
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)];
}
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.
<?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
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.srandom_int
see the link below: https://stackoverflow.com/a/28760905/2891689
Put them in an array and return a random value.