0

I have two arrays one can have example 1 element inside and other array can have 2 elements. So main problem is i got "Undefined offset" error i think its because my arrays elements are different amount file_data loop goes two times and other with only single element goes together and whats why i got this error. How can i fix this problem?

first array is in caption variable

array (size=1)
  0 => string 'Some string' (length=9)

My second array is file_data

array (size=2)
  'userfile_1' => string './uploads/images/131/Untitled.jpg' (length=33)
  'userfile_15' => string './uploads/images/131/unnamed.jpg' (length=32)

$i = 0;

foreach ($file_data as $file)
{
    $image['hotel_id'] = $last_id;
    $image['image']    = $file;
    $image['caption']  = $caption[$i++];

    var_dump($image);
}

In my result i got

array (size=3)
  'hotel_id' => int 132
  'image' => string './uploads/images/132/Untitled.jpg' (length=33)
   'caption' => string 'Some string' (length=9)

 // and here i got this error: Message: Undefined offset: 1


array (size=3)
  'hotel_id' => int 132
  'image' => string './uploads/images/132/unnamed.jpg' (length=32)
  'caption' => null

3 Answers 3

1

You get an undefined offset error due to this

$image['caption']  = $caption[$i++];

To avoid the error:

if(!empty($caption[$i])){
   $image['caption']  = $caption[$i];
} else {
   $image['caption']  = "";
}
$i++;
Sign up to request clarification or add additional context in comments.

Comments

0

May-be that more correct ?

foreach ($file_data as $file)
{
    $image[] =['hotel_id' => $last_id,
               'image'    => $file,
               'caption'  => $caption];
}
var_dump($image);

or replace line:

$image['caption']  = isset($caption[$i++])?$caption[$i++]:"";

Comments

0
$i = 0;

foreach ($file_data as $file)
{
    $image['hotel_id'] = $last_id;
    $image['image']    = $file;
    if($caption[$i++]!='')
        $image['caption']  = $caption[$i++];
    else
        $image['caption']  = '';

    var_dump($image);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.