Mutley Posted April 15, 2007 Share Posted April 15, 2007 How do I select a number randomly? I tried this: <?php $a = array('10','20','30','40'); $b = array_rand($a); echo $b; ?> I want it to echo "10" or "20" etc but instead it comes out with numbers between 1-4? Link to comment https://forums.phpfreaks.com/topic/47125-array_rand/ Share on other sites More sharing options...
ignace Posted April 15, 2007 Share Posted April 15, 2007 <?PHP $a = array('10', '20', '30', '40'); $b = $a[rand(0, count($a) - 1)]; // use mt_rand() to use the Mersenne Twister echo $b; ?> Link to comment https://forums.phpfreaks.com/topic/47125-array_rand/#findComment-229781 Share on other sites More sharing options...
xenophobia Posted April 15, 2007 Share Posted April 15, 2007 <?php $a = array('10', '20', '30', '40'); $b = rand(0, sizeof($a)-1); echo $a[$b]; ?> Link to comment https://forums.phpfreaks.com/topic/47125-array_rand/#findComment-229783 Share on other sites More sharing options...
boo_lolly Posted April 15, 2007 Share Posted April 15, 2007 i'd do it like this: <?php $a = array('10', '20', '30', '40'); shuffle($a); $b = $a[0]; echo $b ."<br />\n"; ?> Link to comment https://forums.phpfreaks.com/topic/47125-array_rand/#findComment-229856 Share on other sites More sharing options...
Barand Posted April 15, 2007 Share Posted April 15, 2007 If you checked the manual you'd see that array_rand() returns KEY not value <?php $a = array('10','20','30','40'); echo $a[array_rand($a)]; ?> Link to comment https://forums.phpfreaks.com/topic/47125-array_rand/#findComment-229858 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.