How can I get the same random array key? I am creating a mad libs type of global. My global set is actually called madLibs.

Within that set, is a matrix field - that can have unlimited blocks. Each block only has two fields. actualRole and pretendRole.

What I have is working - but sometimes I might get the actualRole from one matrix, and the pretendRole from another. Ideally, I'd like to get the same fields from the same random matrix.

{# Get all of the matrix blocks for the global set #}
{% set globalSet = craft.globals.getSetByHandle('madLibs') %}

{% if globalSet|length %}

    {# Find out how many matrix blocks exist #}
    {% set madLibsCount = globalSet.madLib|length %} // 2

    {# Generate a random array key. Remember array is zero based #}
    {% set range = range(0, (madLibsCount - 1)) %}

    &lt;h1&gt;{{ globalSet.madLib[random(range)].actualRole }}&lt;/h1&gt;
    &lt;p&gt;{{ globalSet.madLib[random(range)].pretendRole }}&lt;/p&gt;
{% endif %}


Sometimes, this is happening:

&lt;h1&gt;{{ globalSet.madLib[0].actualRole }}&lt;/h1&gt;
&lt;p&gt;{{ globalSet.madLib[1].pretendRole }}&lt;/p&gt;


I would really like to have this each time:

&lt;h1&gt;{{ globalSet.madLib[0].actualRole }}&lt;/h1&gt;
&lt;p&gt;{{ globalSet.madLib[0].pretendRole }}&lt;/p&gt;


Thank you for any suggestions!
You need to create a common reference to the random number you are creating. Otherwise, you are getting a random number twice - and it's just luck that they show up as expected.

Try this:

{# Get all of the matrix blocks for the global set #}
{% set globalSet = craft.globals.getSetByHandle('madLibs') %}

{% if globalSet|length %}

    {# Find out how many matrix blocks exist #}
    {% set madLibsCount = globalSet.madLib|length %} // 2

    {# Generate a random array key. Remember array is zero based #}
    {% set range = range(0, (madLibsCount - 1)) %}

    {# Capture a single (random) number #}
    {% set key = random(range) %}

    &lt;h1&gt;{{ globalSet.madLib[key].actualRole }}&lt;/h1&gt;
    &lt;p&gt;{{ globalSet.madLib[key].pretendRole }}&lt;/p&gt;
{% endif %}