Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php associative array select 1 random value with key

Tags:

arrays

php

I need to random a single element from the array. I have code ;

     if (isset($_POST['losuj'])) {
   $arr = [
   'chleb' => 'skiny/1.jpg',
   'mienso' => 'skiny/2.jpg',
   'mienso2' => 'skiny/2.jpg',
   'mienso3' => 'skiny/2.jpg',
   'mienso4' => 'skiny/2.jpg',
   'mienso5' => 'skiny/2.jpg',
   'Hasasdasd' => 'skiny/2.jpg',
   ];

     foreach($arr as $key => $value) {
        $keys = array_rand( $arr, 1);
        echo $keys;
     }
 }

And its didnt working. Any tips ?

like image 437
Season6 Avatar asked Jul 04 '26 12:07

Season6


1 Answers

You can use array_keys to get the keys in a indexed array.
The just use array_rand just like you did to pick one and echo the $arr associative key.

$keys = array_keys($arr);
$random = $keys[array_rand($keys,1)];
Echo $random . " => " . $arr[$random];

https://3v4l.org/miacb

like image 67
Andreas Avatar answered Jul 06 '26 02:07

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!