To do it without a page load (i.e. immediately after the button click), you'll have to do it in Javascript (working jsfiddle example here)
<a id="myButton" href="#">
click here to get random stuff
</a>
<div id="myRandomDiv">
</div>
<script type="text/javascript" charset="utf-8">
var randomStrings = [
"hello 1",
"hello 2",
"hello 3",
"hello 4",
"hello 5",
];
var randomDiv = document.getElementById("myRandomDiv");
document.getElementById("myButton").addEventListener("click", function() {
randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
newText = randomStrings[randomIndex];
randomDiv.innerHTML = newText;
});
</script>
To do this instead in PHP (which will require a new page load), you could do this:
<?php
$randomThings = array(
'random thing 1',
'random thing 2',
'random thing 3',
'random thing 4',
'random thing 5',
'random thing 6',
'random thing 7 ',
);
?>
<!-- REST OF YOUR PAGE -->
<?php
echo $randomThings[mt_rand(0,count($randomThings)-1)];
?>
<!-- OTHER STUFF -->
First, we create an array ('list') of random things and store it in the variable $randomThings
.
Elements in an array can be accessed using $variableName[$index]
-- in this case, the indices will simply be 0,1,2,3,4,5,6.
The reason this one-liner (beginning with 'echo') works is, mt_rand
is going to return a random number between 0 and 6, so it'll grab a random element from the $randomThings array. echo
will then spit it to the page.