英文:
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];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论