iBrazilian2
iBrazilian2

Reputation: 2293

How to echo random arrays?

I have the following code that I can't figure out how to echo each value randomly..

<?php
    $c1 = array(
        0 => '#d24726',
        1 => '#bf3317'
    );

    $c2 = array(
        0 => '#14826d', 
        1 => '#0d6856'
    ); 

    $c3 = array(
        0 => '#624f87', 
        1 => '#534373'
    );

    $c4 = array(
        0 => '#008198', 
        1 => '#006e87'
    );

    $c5 = array(
        0 => '#08893e', 
        1 => '#067038'
    );

    $randArray = array($c1,$c2,$c3,$c4,$c5);

    echo '<pre>'; print_r($randArray); echo '</pre>';
?>

Which gives the following output..

Array
(
    [0] => Array
        (
            [0] => #d24726
            [1] => #bf3317
        )

    [1] => Array
        (
            [0] => #14826d
            [1] => #0d6856
        )

    [2] => Array
        (
            [0] => #624f87
            [1] => #534373
        )

    [3] => Array
        (
            [0] => #008198
            [1] => #006e87
        )

    [4] => Array
        (
            [0] => #08893e
            [1] => #067038
        )

)

I want $c1, $c2, $c3, $c4 or $c5 to be chosen randomly and then be able to use their values which are colors..

I tried rand_array which didn't work..

$r = array_rand($randArray);

echo $r[][0];
echo $r[][1];

Upvotes: 1

Views: 117

Answers (2)

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

Your code is right but you will have to specify the key returned by the array_rand().Use the code below

<?php
    $c1 = array(
        0 => '#d24726',
        1 => '#bf3317'
    );

    $c2 = array(
        0 => '#14826d', 
        1 => '#0d6856'
    ); 

    $c3 = array(
        0 => '#624f87', 
        1 => '#534373'
    );

    $c4 = array(
        0 => '#008198', 
        1 => '#006e87'
    );

    $c5 = array(
        0 => '#08893e', 
        1 => '#067038'
    );

    $randArray = array($c1,$c2,$c3,$c4,$c5);
$r = array_rand($randArray);


    echo '<pre>'; print_r($randArray[$r]); echo '</pre>';
?>

Hope this helps you

Upvotes: 0

Rizier123
Rizier123

Reputation: 59691

It works you just have to use it like this:

(array_rand() returns the key, so you just have to use it for the first dimension of the array as key)

$r = array_rand($randArray);

echo $randArray[$r][0];
echo $randArray[$r][1];

For more information about array_rand() see the manual: http://php.net/manual/en/function.array-rand.php

And a quote from there:

When picking only one entry, array_rand() returns the key for a random entry

Upvotes: 1

Related Questions