Click to See Complete Forum and Search --> : foreach help


jrthor2
01-25-2008, 01:46 PM
I am reading the contents of a directory to get a list of images to show in a dropdown box that uses javascript to show the dropdown. My problem is that I need to have a comma at the end of each line, except the last one, so when I get tot he last image, I don't want a comma at the end. Here is the code.

<?
$folder = opendir("../../../images/tinymce/"); // Use 'opendir(".")' if the PHP file is in the same folder as your images. Or set a relative path 'opendir("../path/to/folder")'.
$pic_types = array("jpg", "jpeg", "gif", "png");
$index = array();
list($width, $height, $type, $attr) = @getimagesize($image);
while ($file = readdir ($folder)) {
if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types)) {
array_push($index,$file);
}
}
closedir($folder);
$value = array_values($index);
?>
var tinyMCEImageList = new Array(
<?
foreach($value as $image_file) {
?>
["<?=image_file;?>","<?=print '/~zluthorg/images/tinymce/'.image_file?>"],
<? } ?>
);

thanks

NogDog
01-25-2008, 02:01 PM
Something like this, perhaps?

var tinyMCEImageList = new Array(
<?php
$scriptText = '';
foreach($value as $image_file) {
$scriptText .= "[\"$image_file\",\"/~zluthorg/images/tinymce/$image_file\"],\n";
}
echo rtrim($scriptText, ',');
?>
);

jrthor2
01-25-2008, 02:12 PM
isn't that still going to put a comma after the last image in the list? I want a comma after every item, except the last one.

NogDog
01-25-2008, 02:15 PM
That's why I used the rtrim() in the echo.

Oops, change that to:

echo rtrim($scriptText, ",\n");

jrthor2
01-25-2008, 02:34 PM
Cool, that works. What does rtrim do?

NogDog
01-25-2008, 04:33 PM
http://www.php.net/rtrim