0

How is it possible to pick a random value with PHP from an Array?

Example:

$trees = [
    "appletree" => [
        "id" => "12378", 
        "age" => [15],
        "height" => [6]  
    ], 
    "bananatree" => [
        "id" => "344343453", 
        "age" => [16],
        "height" => [30]
    ],
    "peachtree" => [
        "id" => "34534543",
        "age" => [35],
        "height" => [4]
    ];

How would I access one of the id's randomly? I tried using

$tree_id = array_rand($trees['id']);
echo $tree_id;
echo "\r\n";

but I'm slowly hitting a wall of understanding.

2
  • There is no $trees['id']. There's $trees['appletree']['id'] and $trees['bananatree']['id']. Commented Aug 7, 2021 at 19:53
  • 1
    What you want is array_column($trees, 'id') Commented Aug 7, 2021 at 19:53

2 Answers 2

2

array_rand() returns a random array key. So give it the $trees array to get a tree name, then use that to index the array and access its id property.

$random_tree = array_rand($trees);
echo $trees[$random_tree]['id'];
Sign up to request clarification or add additional context in comments.

Comments

0

maybe this function I created can help:

<?php
    $trees = [
        "appletree" => [
            "id" => "123", 
            "age" => [15],
            "height" => [6]  
        ], 
        "bananatree" => [
            "id" => "456", 
            "age" => [16],
            "height" => [30]
        ],
        "peachtree" => [
            "id" => "789",
            "age" => [35],
            "height" => [4]
        ] // <- you were missing this bracket
    ];
    
    function pickRand($array){
        // Create Temp array
        $temparray = [];
        
        // Iterate through all ID's and put them into out temp array
        foreach($array as $a) $temparray[] = $a['id'];
        
        // Get a random number out of the number of ID's we have
        $rand = rand(0, count($temparray) - 1);
        
        // Return Result
        return $temparray[$rand];
    }
    
    // Use Function
    echo pickRand($trees);

Live Demo: http://sandbox.onlinephpfunctions.com/code/e71dc6b07c3ec93051c69adc66b28aafe555a104

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.