-1

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"

nice_dev
  • 17,053
  • 2
  • 21
  • 35
Chris
  • 833
  • 2
  • 17
  • 37

1 Answers1

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];
nice_dev
  • 17,053
  • 2
  • 21
  • 35
AlonS
  • 683
  • 2
  • 8
  • 16