-1

Problem:

I have a field in my MySQL table with the following value:

9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32

I use PHP to put the value of this field in the variable: $row['Exclude'];

The problem is that I am using a function called rand_except() that looks as following:

function rand_except($min, $max, $except)
{
    //first sort array values
    sort($except, SORT_NUMERIC);

    //calculate average gap between except-values
    $except_count = count($except);
    $avg_gap = ($max - $min + 1 - $except_count) / ($except_count + 1);

    if ($avg_gap <= 0)
     return false;

    //now add min and max to $except, so all gaps between $except-values can be calculated
    array_unshift($except, $min - 1);
    array_push($except, $max + 1);
    $except_count += 2;

    //iterate through all values of except. If gap between 2 values is higher than average gap,
    // create random in this gap
    for ($i = 1; $i < $except_count; $i++)
      if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap)
         return mt_rand($except[$i - 1] + 1, $except[$i] - 1);
    return false;
}

In order for this to work it needs to be like this:

$exclude = array(9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32);      
$_SESSION['experimentversion'] = rand_except(1, 32, $exclude);

Question:

How can I take the database field $row['Exclude'] and transform it into an array so it will work with the function?

Strawberry
  • 33,750
  • 13
  • 40
  • 57
kexxcream
  • 5,873
  • 8
  • 43
  • 62

6 Answers6

2

Simple. Use Explode function.

$s = "1,2,3,4";
$y = explode(",", $s);
print_r($y)
Romit
  • 96
  • 2
  • 13
  • Does not work, it will only randomize numbers between 1-8 and ignore 17-25. No idea why. Is there a problem with the rand_except? – kexxcream Nov 22 '13 at 11:48
  • can you tell me what exactly should your function rand_except do? I mean what is the purpose of the function? – Romit Nov 22 '13 at 12:00
  • I have solved it, I used this function instead: http://stackoverflow.com/questions/2698265/how-to-get-a-random-value-from-1n-but-excluding-several-specific-values-in-php – kexxcream Nov 22 '13 at 12:05
2

There is a explode method in php you can use this method

$string = '1,2,3,4,5';
$array = explode(",",$string);
print_r($array);
it will create an array. 
1
$exclude = explode(', ', $row['Exclude']);
bitWorking
  • 12,485
  • 1
  • 32
  • 38
1
$str = '1,2,3,4,5';
$arr = explode(",",$str);
print_r($arr);
Jim
  • 22,354
  • 6
  • 52
  • 80
1

This should do the trick:

    $exclude = explode(", ", $row['Exclude']);
feddus
  • 356
  • 1
  • 5
1

use explode function.. for more info of Explode Visi this link

 $row = "retrive your value from db";
 $data = explode(", ",$row);
 print_r($data); //here you will get array of your db field
Kalpit
  • 4,906
  • 4
  • 25
  • 43