arrays value string edit and loop in combination with other array and looping

Viewed 31

for each Example 1 caption and some occurrences for the source map

What am I doing wrong?

Images Array

$imgsArray = array(
  'image1-small.jpg', 'image1-medium.jpg', 'image1-large.jpg',
  'image2-small.jpg', 'image2-medium.jpg', 'image2-large.jpg',
  'image3-small.jpg', 'image3-medium.jpg', 'image3-large.jpg'
); // sometimes more pictures too

Captions Array

$imgCaption = array('Adam','Peter'); // if e.g. with 3 pictures only 2 captions are available then I get Notice: Undefined offset:

the code

foreach($imgsArray as $files => $img) {
  // important! $first_char. delete from hyphen to the last string
  $first_char = substr($img,0,strpos($img,"-"));
  ///
  if ($first_char != $last_entry) {
  echo '<p>This is '.$imgCaption[$files];
  echo '<ul>';
    echo '<li>'.$first_char.'-small.jpg</li>';
    echo '<li>'.$first_char.'-medium.jpg</li>';
    echo '<li>'.$first_char.'-large.jpg</li>';
    echo '<li>'.$imgCaption[$files].'</li>';
  echo '</ul>';
  echo '<i>Ciao, '.$imgCaption[$files].'</i><br>---</p>';
  }
  $last_entry = $first_char;
}

unexpected

This is Adam

  • image1-small.jpg
  • image1-medium.jpg
  • image1-large.jpg
  • Adam
Ciao, Adam
---

This is Notice: Undefined offset: 3 in...

  • image2-small.jpg
  • image2-medium.jpg
  • image2-large.jpg
  • Notice: Undefined offset: 3 in...
Ciao, Notice: Undefined offset: 3 in...
---

This is Notice: Undefined offset: 3 in...

  • image3-small.jpg
  • image3-medium.jpg
  • image3-large.jpg
  • Notice: Undefined offset: 6 in...
Ciao, Notice: Undefined offset: 3 in...

---

expected

This is Adam

  • image1-small.jpg
  • image1-medium.jpg
  • image1-large.jpg
  • Adam
Ciao, Adam
---

This is Peter

  • image2-small.jpg
  • image2-medium.jpg
  • image2-large.jpg
  • Peter
Ciao, Peter
---

This is

  • image3-small.jpg
  • image3-medium.jpg
  • image3-large.jpg
  • Susi
Ciao,
---

1 Answers

Can you try my below code

<?php
$imgsArray = array(
  'image1-small.jpg', 'image1-medium.jpg', 'image1-large.jpg',
  'image2-small.jpg', 'image2-medium.jpg', 'image2-large.jpg',
  'image3-small.jpg', 'image3-medium.jpg', 'image3-large.jpg'
);

$imgCaption = array('Adam','Peter','Susi');

$files = 0;

for( $i= 0; $i < count($imgsArray); $i=$i+3 ){
  if(!isset($imgCaption[$files])) break;
  $first_char = substr($imgsArray[$i],0,strpos($imgsArray[$i],"-"));

  echo '<p>This is '.$imgCaption[$files];
  echo '<ul>';
    echo '<li>'.$first_char.'-small.jpg</li>';
    echo '<li>'.$first_char.'-medium.jpg</li>';
    echo '<li>'.$first_char.'-large.jpg</li>';
    echo '<li>'.$imgCaption[$files].'</li>';
  echo '</ul>';
  echo '<i>Ciao, '.$imgCaption[$files].'</i><br>---</p>';

  $files++;
}

Demo link

Related