[英]Illegal offset type error in PHP
Alright, I'm a little lost. 好吧,我有点迷路了。 Here's my code, but how do I get rid of the PHP error that tells me it's an illegal offset type?
这是我的代码,但是如何摆脱告诉我这是非法偏移类型的PHP错误? I'm trying to cycle through the colors.
我试图在颜色之间循环。
$color = array(
[0]=>"red",
[1]=>"cherry",
[2]=>"orange",
[3]=>"amber",
[4]=>"blue",
[5]=>"sapphire",
[6]=>"green",
[7]=>"forest green",
[8]=>"purple",
[9]=>"lavender");
//starts at index 0
for($colorCount=0; $colorCount <=9; $colorCount++){
if ($colorCount == 9){
break;
}
echo implode(", ", $color).", ";
}
I think what might be happening is that, since PHP now supports short-array notation with []
. 我认为可能会发生这种情况,因为PHP现在支持
[]
支持短数组表示法。 It's parsing [0]
as array(0)
which you then try to use as a key in an array, which is not allowed. 它将
[0]
解析为array(0)
,然后尝试将其用作array(0)
中的键,这是不允许的。 This would explain that exact error message. 这将解释该确切的错误消息。
Declare your array like: 像这样声明数组:
$color = array(
0 => "red",
1 => "cherry",
2 => "orange",
3 => "amber",
4 => "blue",
5 => "sapphire",
6 => "green",
7 => "forest green",
8 => "purple",
9 => "lavender"
);
You can even leave off the numbers and do: 您甚至可以忽略数字并执行以下操作:
$color = array(
"red",
"cherry",
"orange",
"amber",
"blue",
"sapphire",
"green",
"forest green",
"purple",
"lavender"
);
$color = array(
'0'=>"red",
'1'=>"cherry",
'2'=>"orange",
'3'=>"amber",
'4'=>"blue",
'5'=>"sapphire",
'6'=>"green",
'7'=>"forest green",
'8'=>"purple",
'9'=>"lavender"
);
foreach ($color as $key => $res) {
print_r($res);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.