Search code examples
phparraysvariablesif-statementrefer

Select a variable from an array


I am new to php arrays. I can not find the solution.

This is my code:

$animals = Array
            (
            1=>$duck,
            2=>$horse,
            3=>$rabbit
            );

            ForEach($animals As $animal) 
            {
                echo $animals[Array_Rand($animals)];
            }

And now I want to select a suitable variable from the array, which is the $rabbit.

Something like:

if($animal[3]){
                echo 'The rabbit just spawned';
            }

I please, tell me how to refer to the variable number 3 (rabbit) using if instruction.


Solution

  • I don't think you need a for each loop for this, just a random to choose from the array:

    https://eval.in/162384

    $animals = Array
                (
                1=>'duck',
                2=>'horse',
                3=>'rabbit'
                );
    $dieroll=array_rand($animals);
    echo "The $animals[$dieroll] just spawned.";
    

    Result:

    The duck just spawned.

    Edit: you mentioned wanting to choose 3 from the array. Then you can use array_rand($x,3):

    https://eval.in/162392

    $animals = Array
                (
                1=>'duck',
                2=>'horse',
                3=>'rabbit',
                4=>'bear',
                5=>'moose'
                );
    $dierolls=array_rand($animals,3);
    // randomize the order of the dierolls:
    shuffle($dierolls);
    foreach($dierolls as $dieroll) {
        echo "Look out, it's a $animals[$dieroll]!\n";
    };
    

    Gives:

    Look out, it's a duck!

    Look out, it's a rabbit!

    Look out, it's a bear!