2016-03-03 36 views
0

好吧,我有點迷路。這裏是我的代碼,但是如何擺脫PHP錯誤,告訴我這是非法的偏移類型?我試圖在顏色中循環。PHP中的非法偏移類型錯誤

$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).", "; 

} 
+2

該數組定義是無效的語法。這是你的實際代碼嗎? – Halcyon

+0

刪除您的索引周圍的括號。 – Sammitch

+0

刪除方括號並加上引號或簡單的數字 –

回答

1

我認爲可能發生的事情是,因爲PHP現在支持與[]短列表符號。它解析[0]array(0),然後嘗試將其用作數組中的鍵,這是不允許的。這將解釋確切的錯誤信息。

聲明你的陣列,如:

$color = array(
    0 => "red", 
    1 => "cherry", 
    2 => "orange", 
    3 => "amber", 
    4 => "blue", 
    5 => "sapphire", 
    6 => "green", 
    7 => "forest green", 
    8 => "purple", 
    9 => "lavender" 
); 

你甚至可以離開過的數字,做:

$color = array(
    "red", 
    "cherry", 
    "orange", 
    "amber", 
    "blue", 
    "sapphire", 
    "green", 
    "forest green", 
    "purple", 
    "lavender" 
); 
+0

好吧!這實際上有很大的幫助,謝謝! – Xiggy

1
$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); 
} 
+0

添加引號不會做任何事情,PHP將解釋鍵看起來像整數作爲整數原始代碼似乎也意味着要使用整數 – Halcyon

+0

作爲第一我只是想說,數組定義是無效的 和我發佈我的答案的原因是..如果他如果數組有效,則需要其他任何東西。謝謝 – santosh