2015-02-07 61 views
-3

當我運行代碼下面我得到 「undefinied offset 4」 時偏移(或5)中的錯誤行:未定義使用 「爆炸」

if ($photo_type == '10') $ifile = $img[4]; else $ifile = $img[5]; 

然而,

echo "$img[4]<br />$img[5]"; 

同時顯示 - $img[4]$img[5]。爲什麼我會收到「未定義的偏移」錯誤?

$imagedata = explode("|", $images); 
$num_images = count($imagedata); 

foreach($imagedata as $image) { 

$img = explode(":", $image); 

if ($photo_type == '10') $ifile = $img[4]; else $ifile = $img[5]; 

echo "$img[4]<br />$img[5]"; 
} 

print_r($img); 
Array ([0] => 6403 [1] => 2 [2] => 1 [3] => c [4] => file1.jpg) 

我不能使用「list」,因爲有時候會有第5個值,有時候不會。當第五個值不存在時,我再次收到「未定義的偏移量」錯誤。

+0

第二線工程,只是因爲它解釋爲純文本和不以任何方式進行評估。 – 2015-02-07 13:55:48

+0

好吧,如果像你所說的那樣,第5個值不存在,那麼當然,當你試圖引用它的時候你會得到一個錯誤。我的建議是:在'$ img = explode(「:」,$ image)後面加上'print_r($ img);'在你嘗試對其進行解引用之前查看你的數組的外觀。 – 2015-02-07 13:56:10

+1

[參考 - 這個錯誤在PHP中意味着什麼?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – 2015-02-07 13:59:09

回答

0

只是更改爲:

if ($photo_type == '10') $ifile = $img[4]; else $ifile = $img[5]; 

if (!isset($img[4])) { 
    echo 'there is no index 4 in'; 
    print_r($img); 
} elseif (!isset($img[5])) { 
    echo 'there is no index 5 in'; 
    print_r($img); 
} else { 
echo "$img[4]<br />$img[5]"; 

} 
0
echo "$img[4]<br />$img[5]"; 

作品,因爲它讀取[4]爲文本,不作爲變量的一部分。相反,你應該使用花括號來封裝變量:

echo "{$img[4]}<br />{$img[5]}"; 

然後,它將無法工作。

偏移4和5不存在意味着explode的輸出不是具有5-6個成員但較少的數組。你可以做一個var_dump($image, $img);看看發生了什麼。

+0

我剛更新了我的帖子。您可以從「print_r」中看到offset4和offset5。 – user1406271 2015-02-07 14:03:48

+0

@ user1406271要完全誠實,我不相信這一點。請將您的整個代碼複製到您的代碼中。因爲你的問題中的代碼應該有效。 – Keelan 2015-02-07 14:08:43

+0

從您的print_r中可以明顯看出偏移量5 **不存在**。 – Keelan 2015-02-07 14:49:38