I would like to produce a variable with the name ‘$slide_show’ to use in an image slider.
I would like ‘value’ of that variable to be a string, and for the particular string value to be based on the specific $file_count generated by the php file counter code I am currently using.
The file counter, of course, is producing a number, based on the number of files in my directory.
In this example… ‘/exampleDirectory/’.
So, for example…
If the $file_count were to be 3, then I would want the output of the ‘$slide_show’ variable to be:
‘1, ‘ . ‘2, ‘ . ‘3’
(htmlentities, including the apostrophes, commas and a single space after the commas).
And if the $file_count were to be 5, then the output of the ‘$slide_show’ variable should be:
‘1, ‘ . ‘2, ‘ . ‘3, ‘ . ‘4, ‘ . ‘5’
…And so on.
With the minimum count option being 1 and the maximum count option being 8.
I am not a php guy, so I am sure there are probably different ways to accomplish what I am trying to achieve. But for now, I am stuck.
Below is the php ‘file counter’ code I am using.
<?php
$dir = '/exampleDirectory/';
$file_count = 0;
if( $handle = opendir($dir) ) {
while( ($file = readdir($handle)) !== false ) {
if( !in_array($file, array('.', '..')) && !is_dir($dir.$file))
$file_count++;
}
}
?>
And this is the actual image slider code:
var img_slider = document.querySelector('.img-slider');
var images = [<?php echo $slide_show; ?>];
var i = 0; // Current Image Index
function prev(){ if(i <= 0) i = images.length; i--; return setImg(); }
function next(){ if(i >= images.length-1 ) i = -1; i++; return setImg();
}
function setImg(){ return img_slider.setAttribute('src',
'/exampleDirectory/' + images[i]); }
3
Answers
You could make a PHP function that generates the string for
$slide_show
based on the amount of files.Then you can use your current image slider code or you can change it to a object:
Then you can call the next and previous image by using the below code
You can use glob to get an array of the files in that folder. Then I use a for loop to loop through the file count and add the number to an array. Then I simply use implode to build the string.
You should not manually craft json strings. Calculate
$file_count
, build the array usingrange()
from 1 with an upper value limit of 8, thenjson_encode()
the generated array, thenecho
it directly into your javascript.