Web Hosting Talk







View Full Version : how do you filter repeating string in php?


latheesan
01-04-2007, 03:30 PM
im writing a script to randomize something called "Item Script".

This is how it looks like:

<?php

$script[] = 'bonus bInt,'. mt_rand(1,5) .';';
$script[] = 'bonus bDex,'. mt_rand(1,5) .';';
$script[] = 'bonus bLuk,'. mt_rand(1,5) .';';
$script[] = 'bonus bStr,'. mt_rand(1,5) .';';
$script[] = 'bonus bDef,'. mt_rand(1,5) .';';
$script[] = 'bonus bVit,'. mt_rand(1,5) .';';
$script[] = 'bonus bCritical,'. mt_rand(6,20) .';';
$script[] = 'bonus bAspdRate,'. mt_rand(6,20) .';';
$script[] = 'bonus bFlee,'. mt_rand(6,20) .';';

$i = 0;
echo '{ ';
while ($i < mt_rand(1,5))
{
echo ($script[mt_rand(0,8)]) . ' ';
$i++;
}
echo '}';

?>

When i run the script, it works fine. The problem is, it sometime uses the same $script again like this:

{ bonus bLuk,4; bonus bFlee,14; bonus bLuk,4; bonus bInt,2; }

As u can see, the $script bonus bLuk,4; got repeated again. How do i filter repeating string like this?

When it's filtered, i want it to look something like this:

{ bonus bLuk,4; bonus bFlee,14; bonus bInt,2; }

sockopt
01-04-2007, 04:58 PM
Perhaps something like this would be sufficient:


$used=array();
while ($i < mt_rand(1,5))
{
$var = $script[mt_rand(0,8)];
if(! in_array($var, $used) ) //this means it's not used
{
echo ($var) . ' ';
$i++;
}
$used[] = $var;
}

latheesan
01-04-2007, 05:07 PM
Brilliant :)

Works exactly how i want it. Thanks allot sockopt.

jimpoz
01-04-2007, 05:10 PM
You might be able to use array_rand to select random elements from an array.

$rand_keys = array_rand($script, mt_rand(1,5));
echo '{';
foreach ($rand_keys as $key) echo ($script[$key]) . ' ';
echo '}';
I've never used array_rand before so I'm not sure if it selects the array items with or without replacement.

You can also use shuffle() to randomly sort the array.

shuffle($script);
echo '{';
$rand = mt_rand(1,5);
$i=0;
foreach ($script as $value) {
echo $value . ' ';
if (++$i==$rand) break;
}
echo '}';