0

Hi I'm trying to find the last array of $linkNumber from my for each loop as i have an image outside the foreach loop that needs the data-slide-index to be the last array plus 1. Any help how to achieve this?

<?php $linkNumber = 0;?>  

<?php foreach ($variables as $variable){ ?>
     <img src="$variable" data-slide-index="$linkNumber++"/>
<?php } ?>
<img src="#" data-slide-index="<?php $linkNumber + 1;?>"
2
  • use array_pop() function of php as this will get last element of array.. Commented Jan 14, 2016 at 11:54
  • count($variables) + 1 Should do it. Commented Jan 14, 2016 at 11:55

3 Answers 3

1

If we ignore that your variables won't be printed or evaluated at all for the moment; essentially what you are doing is correct. Your problem is most of your logic isn't being executed.

You need to explicitly echo variables and evaluations should be inside a PHP block, as follows

<?php
$linkNumber = 0;

foreach ($variables as $variable) :
    ?>
    <img src="<?= $variable; ?>" data-slide-index="<?= $linkNumber; ?>"/>
    <?php
    $linkNumber++;
endforeach;
?>

<img src="#" data-slide-index="<?= $linkNumber; ?>"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i'm an idiot, i had my echo in the foreach but missed it in the one outside it ha
1

This should work:

<?php $linkNumber = 0;?>  

<?php foreach ($variables as $variable){ ?>
 <img src="$variable" data-slide-index="$linkNumber++"/>
 <?php } ?>
 <img src="#" data-slide-index="<?php echo count($variables) + 1;?>"

1 Comment

<img src="$variable" data-slide-index="$linkNumber++"/> will not evalutate.
1

Your code seems to work except for some syntax issues. Eliminating these this code works for me:

<?php
$linkNumber = 0;

$variables = array("test", "test2");

foreach ($variables as $variable){
     echo '<img src="' . $variable . '" data-slide-index="' . $linkNumber++ . '"/>' . "\n";
}
echo '<img src="#" data-slide-index="' . $linkNumber . '">';

?>

http://ideone.com/01cWNg

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.