-3

When I run the code below I get "undefinied offset 4" (or 5) error in the line:

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

However,

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

shows both - $img[4] and $img[5]. Why do I get "undefinied offset" error?

$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 ) 

I can not use "list" because sometimes there is 5th value and sometimes not. When 5th value doesn't exist, I get "undefinied offset" error again.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1406271
  • 297
  • 1
  • 3
  • 12
  • The second line works simply because it's interpreted as plain text and not evaluated in any way. –  Feb 07 '15 at 13:55
  • Well, if, as you say, the 5th value doesn't exist, then, naturally, you'll get an error when trying to reference it. My suggestion: put `print_r($img);` right after `$img = explode(":", $image);` line - to see what your array looks like before you try to dereference it. – Aleks G Feb 07 '15 at 13:56
  • 1
    possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Lorenz Meyer Feb 07 '15 at 13:59
  • Lorenz Meyer, I wrote that this question has been asked but I can not find a solutiuon. – user1406271 Feb 07 '15 at 14:05
  • @user1406271 just put your `print_r($img);` inside the loop `foreach` you will see that not every `$image` has that 4 or 5 elements – Alex Feb 07 '15 at 14:09

2 Answers2

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

Works, because it reads [4] as text, not as part of the variable. Instead, you should use curly braces to encapsulate the variable:

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

And then, it won't work.

That offset 4 and 5 don't exist means that the output of explode wasn't an array with 5-6 members, but less. You could do a var_dump($image, $img); to see what's going on.

  • I just updated my post. offset4 and offset 5 exist as you can see from "print_r". – user1406271 Feb 07 '15 at 14:03
  • @user1406271 to be completely honest, I don't believe this. Please copy your whole code as you're trying it now to your code. Because the code you have in your question should work. –  Feb 07 '15 at 14:08
  • From your print_r it's clear that offset 5 **does not exist**. –  Feb 07 '15 at 14:49
0

Just change to:

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]";

}
Alex
  • 16,739
  • 1
  • 28
  • 51