skip to Main Content

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


  1. 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.

    $dir = '/exampleDirectory/';
    $files = glob( $dir ."*" );
    
    $slide_show = [];
    
    if($files) {
        for($z = 1;$z<=count($files);$z++){
            $slide_show[] = $z;
        }
    }
    
    $slide_show =  "'" . implode(",'.'",$slide_show) . "'";
    echo $slide_show;
    
    Login or Signup to reply.
  2. You should not manually craft json strings. Calculate $file_count, build the array using range() from 1 with an upper value limit of 8, then json_encode() the generated array, then echo it directly into your javascript.

    var images = <?php echo json_encode(range(1, min($file_count, 8)); ?>;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search