“Random item from PHP array = ‘access array offset'”

huangapple go评论49阅读模式
英文:

Random item from PHP array = "access array offset"

问题

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

$shuffled = shuffle($colors);
print_r($shuffled[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"

答案1

得分: 2

shuffle() 返回一个布尔值,表示洗牌是否成功。因此,$shuffled 是一个布尔值,而不是一个数组。您可以使用 array_rand() 函数,它会从数组中返回一个随机键。


$keys = array_keys($colors);
$random_key = $keys[array_rand($keys)];
echo $colors[$random_key];
英文:

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];

huangapple
  • 本文由 发表于 2023年4月11日 13:00:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定