2015-02-07 59 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