Jump to content

What's an easy way to generate statistics?


benphp

Recommended Posts

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?

<?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));
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.