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?

Link to comment
Share on other sites

<?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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.