PHP限制文件夹项列表的循环迭代

I am trying to limit the iterations of a foreach loop to display only 4 items contained in a folder, instead of all, however at the moment it keeps displaying all items:

<?php
$dir    = 'images';
$images = scandir($dir);
$i=0;
foreach($images as $file){
    if ($i == 4) {
        break;
    }
    $pos = strpos($file, '-s.jpg');
    if ($pos !== false) {
        echo '<a href="/images/'.$file.'"><img src="/images/'.$file.'"/></a>';
    } // end if strpos
    $i++;
} // end foreach
?>

foreach loop in php iterate through all the array. So you need to make a for loop to make it work. This way should be good :

<?php
$dir    = 'images';
$images = scandir($dir);
for($i=0;$i<4;$i++){
    $pos = strpos($images[$i], '-s.jpg');
    if ($pos !== false) {
        echo '<a href="/images/'.$images[$i].'"><img src="/images/'.$images[$i].'"/></a>';
    } // end if strpos
} // end for
?>

This works, had to include the $i++ inside the strpos check, and change to "if($i>4){...}":

<?php
$dir    = 'images';
$images = scandir($dir);
$i=1;
foreach($images as $file){
    if ($i>4){
      break;
    }
    $pos = strpos($file, '-s.jpg');
    if ($pos !== false) {
        echo '<a href="/images/'.$file.'"><img src="/images/'.$file.'"/></a>';
        $i++;
    } // end if strpos
} // end foreach
?>