Static Variable within a Snippet

Hi!

I’m trying to write a plugin that builds a small array of values, randomizes that array once, and then returns the values, one after another. Is there a way to define a value that remains static each time a snippet is called to prevent the array from getting shuffled each time? Or a way to define the array and shuffle it outside the snippet itself?

My instinct was something like this, but it doesn’t work:

if (!@$shuffled) {
    static $shuffled = true;
    shuffle($array)
}

Perhaps there is a better way to accomplish this?

I’m probably missing something, but where’s the point of shuffling it if it remains static afterwards?

I am hoping to produce a randomized sequence of variables on each given page:

So something like (in pseudo code):

$colors = ['red', 'white', 'blue'];
shuffleOnce($colors);
echo $colors[0];
array_shift($colors);

And then in a template:

Color One: <?php snippet('getColor'); ?>
Color Two: <?php snippet('getColor'); ?>
Color Three: <?php snippet('getColor'); ?>

Well, one part would be. to pass the key to the snippet:

Color One: <?php snippet('getColor', ['key' => 1]); ?>
Color Two: <?php snippet('getColor', , ['key' => 2]); ?>
Color Three: <?php snippet('getColor', , ['key' => 3]); ?>

In your snippet

$colors = ['red', 'white', 'blue'];
shuffle($colors);

But when is this supposed to be shuffled?

1 Like

Thanks for this!

The shuffling would happen once, upon page load so that the sequence on one page might be: red, white, blue and on another page: white, red, blue.

1 Like

Hmmm. (Okay, related to this, but outside of snippets:)

How would I echo out one of the items chosen from within a Multiselect Choices page Field …randomly?

<?php $single = $page->choices()->shuffle()->first() ?>
<p>Your random choice is <?php $single->kirbytext() ?></p>

A multiselect field stores it’s content as a comma separated list.

  1. So you get an array of all choices like this:
$choices = $page->choices()->split(',');
  1. You can now use PHP’s shuffle function:
shuffle($choices);
  1. Then get the first item
$item = $choices[0];

The alternative would be to convert the array to a collection after the first step:

$item = (new Collection($choices))->shuffle()->first();
1 Like

Thank you!