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:
- 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 ).
- 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.
Advertisement
Answer
You can take advantage of the array_splice function that removes elements from the array everytime it returns those elements :
$files = glob("layout/gallery/*.jpg"); rsort($files, SORT_NATURAL); // split the files in rows $rows = []; while(count($files) != 0) { // even rows have 5 elements, odd ones have 4 $num_files_to_splice = count($rows) % 2 == 0 ? 5 : 4; $rows[] = array_splice($files, 0, $num_files_to_splice); } // display them accordingly foreach($rows as $row) { foreach($row as $file) { echo '<img src="'.$file.'">'; } echo '<br><br>'; }