benphp Posted February 5, 2010 Share Posted February 5, 2010 For example, 51% of the population is Female. How would you illustrate that with a random function? Here's my first attempt. I'm sure there are other, maybe better ways. <?php //51% of the population is women. $gender = rand(1,102); if($gender > 50) { $gender = "Female"; } else { $gender = "Male"; } ?> Now that I think about it, I'll probably have to write a more complex function. If I have statistics like: Ice Cream Flavors - 10% like strawberry 10% like cherry 10% like mint 40% like chocolate 30% like vanilla How would I write something that would generate a random sample? Quote Link to comment Share on other sites More sharing options...
teamatomic Posted February 5, 2010 Share Posted February 5, 2010 put the stats into an array and use array_rand. HTH Teamatomic Quote Link to comment Share on other sites More sharing options...
RussellReal Posted February 5, 2010 Share Posted February 5, 2010 <?php function statistics($array) { $c = 100; $stats = array(); $loop = 0; foreach ($array as $val) { if ($loop != (count($array) - 1)) $c = ($c - ($e = rand(0,($c / (count($array) - $loop++))))); else $e = $c; $stats[] = $e; } shuffle($stats); return array_combine($array,$stats); } $arr = array( 'Strawberry', 'Cherry', 'Vanilla' ); print_r(statistics($arr)); ?> Quote Link to comment 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.