Notice: Undefined offset: different rows

I'm trying to display images' metadata stored in 2 arrays…
When images has no Name, I'd like to display "no-name" instead. Here's how I display those now:

$imgs = array('img 1','img 2','img 3','img 4','img 5','img 6');
$imgNames = array('name 1','name 2','name 3',);

foreach($imgs as $files => $img)
{
    echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';
};

I expect the output:

Image: img 1 and Name: name 1
Image: img 2 and Name: name 2
Image: img 3 and Name: name 3
Image: img 4 and Name: no-name
Image: img 5 and Name: no-name
Image: img 6 and Name: no-name

but actual output is:

Image: img 1 and Name: name 1
Image: img 2 and Name: name 2
Image: img 3 and Name: name 3
Notice: Undefined offset: 3 in XX.php …
Image:img 4 and Name: 
Notice: Undefined offset: 4 in XX.php …
Image:img 5 and Name: 
Notice: Undefined offset: 5 in XX.php …
Image:img 6 and Name: 

How can I fix this to display the default "no-name" strings?

2 answers

  • answered 2019-04-21 09:58 Danyal Sandeelo

    ImagNames has 3 elements while the other array has 5 elements.

    You can add a check not to print it, if key doesn't exist

    foreach($imgs as $files => $img)
    {
    
     if(array_key_exists($files,$imgNames){
    
       echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';
     }
    };
    

  • answered 2019-04-21 10:00 Zain Farooq

    You can use isset() for this purpose. $imgNames array contains three elements while $imgs contains six and you have looped through the $imgs which means that it will run six times leaving $imgNames undefined for some of its elements. If isset() function returns false for current $files like $imgNames[$files] then it will be assigned a string 'no-name'

        <?php
    $imgs = array('img 1','img 2','img 3','img 4','img 5','img 6');
    $imgNames = array('name 1','name 2','name 3',);
    
    foreach($imgs as $files => $img)
    {
      if(!isset($imgNames[$files]))
      {
        $imgNames[$files] = 'no-name';
      }
    echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';
    }
    ?>
    

    Here is the demo