John Davidson

web - Display pictures from a folder in the specific way - PHP

0 comments
Message:


I am trying to create a dynamic gallery in php with specific order of pictures on the page, but I can't find the function or piece of php code to do so.


Conditions:



  1. The gallery must be dynamic, pictures will be coming from a folder via php, because when I'll add/upload more pictures in the folder they must be displayed on the page without adding manually the html tags in. ( this part is easy, problem is the condition 2 ).

  2. The first row will have 5 pictures, the second - 4 pictures (important for the specific effect).


My code:


    $files = glob("layout/gallery/*.jpg");

rsort($files, SORT_NATURAL);

for ($i=0; $i < count($files); $i++) {

for( ; $i<5; $i++){
$one = $files[$i];
echo '<img src="'.$one.'">' . '<br><br>';
}

echo '<br>';

for( ; $i<9; $i++){
$two = $files[$i];
echo '<img src="'.$two.'">' . '<br><br>';
}

}

The code works well, but it just displays 9 pictures obviously. I was unable to make it dynamic displaying 5 pictures first, 4 pictures after and stay this way in a loop till displays all pictures from that folder.



My Answer:
'path/to/folder/*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$count = 0;
foreach ($files as $file) {
if ($count % 5 == 0) {
echo '
';
}
echo '
';
$count++;
if ($count % 5 == 0) {
echo '
';
}
}

if ($count % 5 != 0) {
echo '
';
}

if ($count % 5 != 0) {
echo '
';
foreach ($files as $file) {
if ($count % 4 == 0) {
echo '
';
}
$count++;
}
echo '
';
}

This code will display the pictures in rows of 5 and 4 as specified. The first row will have 5 pictures and the second row will have 4 pictures. The code uses the glob function to get all the image files from a specific folder and then loops through them to display them on the page. The count variable is used to keep track of the number of pictures displayed and to determine when to start a new row.

Rate this post

3 of 5 based on 7812 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us