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? Link to comment https://forums.phpfreaks.com/topic/191089-whats-an-easy-way-to-generate-statistics/ 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 Link to comment https://forums.phpfreaks.com/topic/191089-whats-an-easy-way-to-generate-statistics/#findComment-1007597 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)); ?> Link to comment https://forums.phpfreaks.com/topic/191089-whats-an-easy-way-to-generate-statistics/#findComment-1007606 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.