First, you mention a list; this directly translates to an array.
Second, you have a finite number of options, presented in the array, and you want to pick one at random. This translates to picking an index (integer) at random. Since arrays start at 0 and you cannot choose an item passed the last index, you will then need to choose a random range between 0 and the length of the array.
If you simply want to get a random item from a list from pressing a button, you'll most certainly want to isolate this to the front-end, i.e. javascript:
var randomWords = [
'Apple',
'Banana',
'Pear'
];
function getRandomWordFromList(list) {
var index = getRandomInt(0,list.length);
return randomWords[index];
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.getElementById('myButton').onclick = function() { // for example's sake...
document.getElementById('theOutput').innerHTML = getRandomWordFromList(randomWords);
};
(getRandomInt
from Generating random whole numbers in JavaScript in a specific range?)
Also, if your array is fragmented (i.e. some indices are missing), you can use (safer, albeit more convoluted):
function arrayKeys(array) {
var i,keys = [];
for ( i in array ) {
if ( isInt(i) && array.hasOwnProperty(i) ) {
keys.push(i);
}
}
return keys;
}
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomWordFromList(list) {
var keys = arrayKeys(list); // be sure to only get indices that exist
var key = getRandomInt(0,keys.length-1);
return list[keys[key]];
}
var randomWords = [
'Apple',
'Banana',
'Pear'
];
delete randomWords[1]; // remove 'Banana'
var theWord = getRandomWordFromList(randomWords);
If there is something server-side that influences the randomized list, you can populate the randomWords array via PHP as follows:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
?>
<script type="text/javascript">
var randomWords = [<?php echo "'".implode("','",$randomWords)."'"; ?>];
// don't forget your getRandomWord functions
</script>
Bonus: If the randomization must happen entirely server-side, i.e. php, here is a translation:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
echo $randomWords[array_rand($randomWords)]; // output somewhere
?>