Reputation: 128
I need to show automatic words when loading a page on my site. I have managed to show a word, but I can not see more than one. It is important that the words do not repeat themselves.
I have this code where I specify each word.
<?php
$randomThings = array(
'random thing 1',
'random thing 2',
'random thing 3',
'random thing 4',
'random thing 5',
'random thing 6',
'random thing 7 ',
);
?>
And finally I paste this code where I want it to be displayed.
<?php echo $randomThings[mt_rand(0,count($randomThings)-1)]; ?>
As I say, a word shows it to me correctly but I want to show more than one.
Thank you very much, sorry for my English
Upvotes: 0
Views: 1483
Reputation: 7485
Just shuffle, and then pop or shift:
<?php
$things =
[
'The early bird catches the worm.',
'Two wrongs don\'t make a right.',
'Better late than never.'
];
shuffle($things);
while($item = array_pop($things))
echo $item, "\n";
Example output:
Better late than never.
The early bird catches the worm.
Two wrongs don't make a right.
Or make a generator:
$generator = function($things) {
shuffle($things);
return function() use (&$things) {
return array_pop($things);
};
};
$thing = $generator($things);
echo $thing();
Upvotes: 1
Reputation: 1615
Here is the snippet, provide number of elements as second parameter in rand_keys:
<?php
$input = array(
'random thing 1',
'random thing 2',
'random thing 3',
'random thing 4',
'random thing 5',
'random thing 6',
'random thing 7 ',
);
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]];
echo $input[$rand_keys[1]];
?>
Upvotes: 1
Reputation: 1106
You can make it this way :
<?php echo array_shift( $randomThings ); ?>
The array_shift()
method takes the first element of an array and take it out of the array.
If ou want to make it random, you can use the shuffle()
function on your array to shuffle it before doing the array_shift.
here is the php doc for shuffle() here is the php doc for array_shift()
Upvotes: 1