PHP在5个变量之间平均切换

So I am looking to alternate between 5 different variables but want the 'load' to be equal on each variable. I have seen it done with just two variables and alternating based on random number generated withe limits being set. But trying to expand that idea on to five variables. Thanks in advance.

Just for example purposes say I had 5 images and wanted each image to be shown equally after 100 tests. This is the easiest way I can think of explaining it.

This is how I did it with only 2 variables but trying to think about how to do it with more.

$ad1 = '<img src... >';
$ad2 = '<img src...2 >';

echo mt_rand(0, 1) ? $ad1 : $ad2;

Source:PHP Switching between two variables equally without using database

So this is what I have going just want to know what the ideas on equally being between the different variables.

$input = array("a", "b", "c", "d");
$rand_keys = array_rand($input);
echo 'var key ="'.$input[$rand_keys].'"';

If you want a random pick out of a set you can use array_rand().

$images = array( '<img src="img1.png">', '<img src="img2.png">', '<img src="img3.png">', '<img src="img4.png">', '<img src="img5.png">' );

$pick = array_rand( $images );

$pick will be a random key from the $images array.

This is easily extensible as you can keep adding elements to the array. Here I am of course following your example of adding the <img> tag to the array but you could just as easily add only some identifier to the array.

I would suggest using a Class to handle each "object":

<?php
  ...
  ...
  class RandObjClass
  {
     var $myCounter = 1;
     var $mySeed = time();
     var $myReference = "...path-to-image-file..."; # Image for example
     function getWeight() {
        srand($mySeed);
        $myWeight = $this->myCounter * rand();
        return($myWeight);
     }
     setSeed($xSeed) {
        $this->mySeed = $xSeed;
     }
  }
...
...

Fill an array of x "RandObjClass" objects and use the "getWeight" to select the next one of "highest" weight.

You can play with affecting the weight via various methods, like counting. This can influence which is chosen next.

Two options below, because your question is titled "swithcing between 5 variables equally" - There is an equal distribution solution and a randomized solution.

Notice you need apc installed for the equal rotation solution to work. It is a fairly common php module and can be installed quite easily if you have permission to do so:

Redhat/centos : yum install php-apc

Ubuntu: sudo apt-get php-apc

If you are using shared hosting and they don't have apc installed then this won't work for you :(

<?php

//If you want perfectly equal distribution.
$variables = array('a', 'b', 'c', 'd', 'e');
if (!($this_var = apc_fetch('last'))) $this_var = 0;
echo $variables[$this_var];
$this_var++;
$this_var = $this_var % 5;
apc_store('last', $this_var);


//If you want random distribution
$variables = array('a', 'b', 'c', 'd', 'e');
$index = mt_rand(0, 4);
echo $variables[$index];