2

I have a jquery function which relies on an array of images to create a fadeOut/In effect.

The line of code looks like this:

var images=new Array('/images/myImage1.jpg','/images/myImage2.jpg','/images/myImage3.jpg');

Currently I manually create this array but I would like to create it using php to grab the images in a directory on my server. I have found the following code which does this but I need to format so it looks like the javascript above.

<?php
$dir    = 'chamberImages/portfolio';
$files2 = scandir($dir, 1);
print_r($files2);
?>
0

3 Answers 3

6

You could just JSON encode the array that you have in $files2, removing the . and .. entries with array_slice:

var images = <?php echo json_encode(array_slice($files2, 2)); ?>;
2
  • This seems to be almost what I need but it results in var images=new Array["image1.jpg","image2.jpg","image3.jpg"]; rather than var images=new Array('image1.jpg','image2.jpg','image3.jpg'); which is what I need to get this working... Commented May 16, 2011 at 13:01
  • 2
    @Tom You don't need the new Array stuff. var images=['x.jpg', 'y.jpg']; format is perfectly fine. Commented May 16, 2011 at 13:12
1

You can use json:

json_encode($files2);

The result is a json formatted string that can be used as javascript code to create the array.

1

Use ajax. If you can't or do not want to do it, here is an inline PHP solution:

var images=new Array('<?php echo implode("', '", $files2) ?>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.