简体   繁体   中英

Get the last array index after a foreach loop

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM