1

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];

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.