Martin
Martin

Reputation: 31

php show data from an array in an order instead of random

I am showing data from an array in random using rand() . Is it possible to show the data in a systematic order instead of random ?

$one = data1;
$two = data2;
$three = data3;
$myarray = array($one, $two, $three)
$show = $myarray[rand(0,2)];

Note the $show variable is called dynamically in page & it outputs values of $myarray at many places on page

Ex. It outputs above array in random orders as data2,data1,data3,data3,data2,data1......

How do i code the above so that the result on page will be in a systematic order i.e. first to be shown will be the 1st value of array i.e. data1 then data2 then data3 then again data1 then data2 then data3 & so on...

Upvotes: 0

Views: 99

Answers (2)

Jeto
Jeto

Reputation: 14927

You may make use of a InfiniteIterator for this purpose. It iterates normally then loops back over to the beginning and so on.

It also uses static variables to retain state across subsequent calls.

This becomes:

add_action('mycustomlink', function ($link) {
  if ($link->is_external()) {
    $externalUrl = $link->get_attr('href');

    static $urls = [
      'https://example1.com?=',
      'https://example2.com?=',
      'https://example3.com?='
    ];

    /** @var Iterator $urlsIterator */
    static $urlsIterator;

    if (!isset($urlsIterator)) {
      $urlsIterator = new \InfiniteIterator(new \ArrayIterator($urls));
      $urlsIterator->rewind();
      $url = $urlsIterator->current();
    } else {
      $urlsIterator->next();
      $url = $urlsIterator->current();
    }

    $link->set_attr('href', $url . $externalUrl);
  }
}, 10, 1);

Note that I took the liberty of refactor your code to be more PHP7-friendly syntax while I was at it.

Demo (of the function): https://3v4l.org/sq2Gk

Upvotes: 1

Barmar
Barmar

Reputation: 780851

Use a session variable to save the array index, which you increment each time.

session_start();
$one = data1;
$two = data2;
$three = data3;
$myarray = array($one, $two, $three)
if (isset($_SESSION['myarray_index'])) {
    // increment with wraparound
    $myarray_index = ($_SESSION['myarray_index'] + 1) % count($myarray);
} else {
    $myarray_index = 0;
}
$_SESSION['myarray_index'] = $myarray_index;
$show = $myarray[$myarray_index];

Upvotes: 0

Related Questions