If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Biased Percentages Based On Array

I need to explode this string twice and put in an array so that I can have the array look like this:

$items=array("item1" => "20", etc...)

Then I will have the script generate a random number between 1 and 100 and if that number determines the item that is chosen based on its percentage value, it saves that value as another final variable.

Given time, I would probably simplify this some. But here's a fairly good approach assuming I understand the question:

PHP Code:

<pre><!-- see below comment on the closing /pre tag (this is for visual formatting) --><?php$string="item1.20|item2.60|item3.20";$ar1 = explode('|', $string);$percent = 0;foreach($ar1 as $item){$ar2[] = explode('.', $item);$ar2[count($ar2) - 1][1] = ($percent += $ar2[count($ar2) - 1][1]);}$rnum = rand(1, $percent);$randomresult = $ar2[0][0];print_r($ar2); // just so you can see the multidimensional array, may be removed or commented outforeach ($ar2 as $items){ if($rnum <= $items[1]){$randomresult = $items[0]; break; }}echo "\n$rnum"; // just so you can see the random number, may be removed or commented outecho "\n$randomresult"; // this is the result. You can leave this line as is, or comment it out/remove it and do something else later with $randomresult?></pre> <!-- the pre tag is just for visual formatting, if you are doing other thins with the code that either have their own format, or that aren't visual, it can be removed -->

Last edited by jscheuer1; 11-20-2014 at 06:29 AM.
Reason: minor code improvement - now allows any number as total percentage