是什么让这项工作?

I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.

/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;

/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
    $index++;
    $thumbnail_image = $thumbs_dir.$file;
    if(!file_exists($thumbnail_image)) {
        $extension = get_file_extension($thumbnail_image);
        if($extension) {
            make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
        }
    }
    echo '<a href="',$images_dir.$file,'" class="photo-link smoothbox" rel="gallery"><img src="',$thumbnail_image,'" /></a>';
    if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}

I understand how everything with the exception of this line works.

if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }

I know it is getting its value from this line:

$images_per_row = 3;

But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.

Any answers at all would be appreciative!

$index % $images_per_row == 0

The % means "mod", example 4 mod 2 = 0.

A % B = the remainder when we divide A by B.

In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.

Hope it helps!

% is the modulo operator. It divides the two numbers and then returns the remainder after the division.

It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.

So, if we make 5 % 2 into a fraction and reduce it:

 5       1  (this is the remainder)
--- → 2 ---
 2       2

So, 5 % 2 = 1.

If we take 8 % 3 we can do the same thing:

 8       2 (this is the remainder)
--- → 2 ---
 3       3

So, 8 % 3 = 2.

If there is no remainder, such as in 9 % 3 then you will get 0 back. See:

 9       0 (this is the remainder)
--- → 3 ---
 3       3

You can write some PHP to see what the values are when doing the modulo operations:

$perRow = 3;
for ($i = 0; $i < 10; $i++) {
    echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "
";
}

Output:

0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3