Altec Posted June 14, 2009 Share Posted June 14, 2009 I'm using this code to pull random slogans to display on my site: <?php $slogans = array( 'rawr1', 'rawr2', 'rawr3' ); echo $slogans[floor(rand(0,count($slogans)))]; ?> However, sometimes it doesn't return anything (nothing is echo'd out). Why is that, and is there a better way to do this? Quote Link to comment https://forums.phpfreaks.com/topic/162172-solved-rand-issue/ Share on other sites More sharing options...
Andy-H Posted June 14, 2009 Share Posted June 14, 2009 <?php $slogans = array( 'rawr1', 'rawr2', 'rawr3' ); $slogans = shuffle($slogans); echo $slogans[0]; ?> Quote Link to comment https://forums.phpfreaks.com/topic/162172-solved-rand-issue/#findComment-855798 Share on other sites More sharing options...
Altec Posted June 14, 2009 Author Share Posted June 14, 2009 Ran into a slight issue. I'm not getting any output. EDIT: It returns a boolean only; took out the variable definition. EDIT2: Use this instead: echo $slogans[array_rand($slogans)]; Quote Link to comment https://forums.phpfreaks.com/topic/162172-solved-rand-issue/#findComment-855803 Share on other sites More sharing options...
Andy-H Posted June 14, 2009 Share Posted June 14, 2009 <?php $slogans = array( 'rawr1', 'rawr2', 'rarw3' ); shuffle($slogans); echo $slogans[0]; ?> Edit: Thats why, it takes a reference and returns boolean, lol sorry, that will work =P Quote Link to comment https://forums.phpfreaks.com/topic/162172-solved-rand-issue/#findComment-855810 Share on other sites More sharing options...
Alex Posted June 14, 2009 Share Posted June 14, 2009 You can use what you were using by have to add an offset of -1. $slogans[(rand(0,count($slogans)-1)]; This is because arrays start at [0], and count returns the number of elements in the array. In your case 3. Sometimes it could come out with $slogans[3], when your array only includes $slogans[0]-[2] Quote Link to comment https://forums.phpfreaks.com/topic/162172-solved-rand-issue/#findComment-855821 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.