0

Im trying to get a single random key => value from an array but im getting the following error. Any ideas what im doing wrong?

$colors = array("Yellow Sun" => "FAE500", "Golden" => "fab600", "Orange Juice" => "FF6D00", "Photo Blue" => "A2E5F4");


$shuffled = shuffle($colors);
print_r($shuffled[0]);

"Warning: Trying to access array offset on value of type bool in"

2
  • 1
    You don't have an index of 0. The color names are your indexes. Commented Apr 11, 2023 at 5:05
  • 1
    Also shuffle() returns true or false. See php.net/manual/en/function.shuffle.php Commented Apr 11, 2023 at 5:07

1 Answer 1

2

shuffle() returns a boolean value indicating whether the shuffle was successful or not. Therefore, $shuffled is a boolean value and not an array. You can use the array_rand() function which returns a random key from an array.

<?php

$keys = array_keys($colors);
$random_key = $keys[array_rand($keys)];
echo $colors[$random_key];
Sign up to request clarification or add additional context in comments.

4 Comments

that worked! TY - however I need to access the ket value pair?
this appears to only give the value. I need both. Any ideas :)
@Chris The key in this example is $random_key…!
TY I just can't seem to get the key, only the value shows up. I'll keep at it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.