Support Forums

Full Version: Having trouble with arrays.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to execute the array randomly, but how can I do it in this form of example?

PHP Code:
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare"

How can I make it echo randomly, 1-4?
echo (array_rand($employee_array,1));

That should work.
(09-17-2010, 01:17 AM)Omniscient Wrote: [ -> ]echo (array_rand($employee_array,1));

That should work.

Oh fudge. I've been doing it the hard way.

PHP Code:
$count count($arr) - 1;
$rand rand(0$count);
echo 
$arr[$rand]; 
(09-17-2010, 01:17 AM)Omniscient Wrote: [ -> ]echo (array_rand($employee_array,1));

That should work.
I didnt know there were such function, That kills the time.

Thanks!
(10-06-2010, 01:51 PM)Orgy Wrote: [ -> ]Oh fudge. I've been doing it the hard way.

PHP Code:
$count count($arr) - 1;
$rand rand(0$count);
echo 
$arr[$rand]; 

Orgy always does at the hard way.
(10-08-2010, 03:51 AM)ariton Wrote: [ -> ]Orgy always does at the hard way.

Nothing better than sending code to someone that makes them say, "What the fudge? Why is he doing this?"
(10-08-2010, 04:35 AM)Orgy Wrote: [ -> ]Nothing better than sending code to someone that makes them say, "What the fudge? Why is he doing this?"

Every once in a while I will run across a code review request at work (all major commits need code reviews) that makes me say something along the same line. Oddly enough the person who made the commit is almost always an intern.

Another alternative to the array_rand () method, if you're using the entire array and don't need to pull out random indices, is the shuffle () method. It does as its name suggestions: randomizes the order of the array elements.
(10-08-2010, 04:46 AM)Disease Wrote: [ -> ]Every once in a while I will run across a code review request at work (all major commits need code reviews) that makes me say something along the same line. Oddly enough the person who made the commit is almost always an intern.

Another alternative to the array_rand () method, if you're using the entire array and don't need to pull out random indices, is the shuffle () method. It does as its name suggestions: randomizes the order of the array elements.

I remember when I first discovered shuffle(). It was so great, although now I can't remember why I needed it.
Wow, Omniscient came up with the goods. Nice work Omni!