behnampmdg3's avatar

Basic Split Test Without DB Access

Hi;

I want to send half of the traffic to Yahoo and have to Google.

1 - Is this way of redirecting correct? 2 - Anyways to make the distribution 100% accurate?

Thanks

$rand=rand(1,2);

$url = "https://yahoo.com";
if($rand==1)
{
  $url = "https://google.com";
}  
header('Location: '.$url);
0 likes
4 replies
douglasakula's avatar

@behnampmdg3

Check out this script.

for ($index = 1; $index <= 1000; $index++) {
        $rand[] = rand(1,2);
      }
      
      dump(count(array_filter($rand, function ($value) { return $value == 1; })));
      dump(count(array_filter($rand, function ($value) { return $value == 2; })));
      
      $rand = [];
      
      for ($index = 1; $index <= 1000; $index++) {
        if($index % 2 == 0){
          array_push($rand, 2);        
        } else {
          array_push($rand, 1); 
        }
      }
      
      dump(count(array_filter($rand, function ($value) { return $value == 1; })));
      dump(count(array_filter($rand, function ($value) { return $value == 2; })));      

The first for loop works as you have your script above and the distribution is not equal - it can be 400, 600. The second one the distribution is equal - 500,500. So to answer your question - if you are to distribute the traffic evenly - you are better of not using a randomn number to make the decision.

I would rather you have a variable that you increment when sending traffic to google and decrement when sending it to yahoo - then you always check this value before making the decision to route traffic.

douglasakula's avatar

So something like this would evenly distribute

for ($index = 1; $index <= 10; $index++) {
        $checker = empty($checker) ? 1 : $checker;

        if($checker % 2 == 0){
          $url = "https://yahoo.com";
          $checker-=1;
          dump($url);
        } else{
          $url = "https://google.com";
          $checker+=1;
          dump($url);
        }
   }

Depending on your use case $checker could be in a session or a database value.

behnampmdg3's avatar

But guys I don't have a database.

Also visitors are from all around the world.

It's not on one computer.

douglasakula's avatar

@behnampmdg3 - Is the system online - because all this visitors would hit 1 server. Thats where you can put / have your database or session management.

Again it depends with your use case. To answer your original question - the rand() would not distribute evenly - try it in 10 or 100 loops as I have given example above and you will clearly see this.

So if you are to do this well - you need another solution a part from rand()

Please or to participate in this conversation.