Link to home
Start Free TrialLog in
Avatar of Kyle Hamilton
Kyle HamiltonFlag for United States of America

asked on

echo implode (",", $array) question

I have this little script to scan a directory of images. I want to write the image names into a javascript array.

I almost have it, but the problem is I get a trailing comma after the last item in the array.

So, is there a way to use implode instead of the way I did it?

<?PHP
  // filetypes to display
  $imagetypes = array("image/jpeg", "image/gif");
?>
    <?PHP
  // Original PHP code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  function getImages($dir)
  {
    global $imagetypes;

    // array to hold return value
    $retval = array();

    // add trailing slash if missing
    if(substr($dir, -1) != "/") $dir .= "/";

    // full server path to directory
    $fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";

    $d = @dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
    while(false !== ($entry = $d->read())) {
      // skip hidden files
      if($entry[0] == ".") continue;

      // check for image files
      if(in_array(mime_content_type("$fulldir$entry"), $imagetypes)) {
        $retval[] = array(
         "file" => "/$dir$entry",
         "size" => getimagesize("$fulldir$entry")
        );
      }
    }
    $d->close();

    return $retval;
  }
?>
    <?PHP
  // fetch image details
  $images = getImages("webDesign");

  
  
  
  // display on page
  echo "<script>var imgArr = [";
  foreach($images as $img) {
    
    echo   "\"{$img['file']}\",\n"; // this is giving me a trailing comma
   
    //echo implode (",\n ", $images); // this is returning [Array, Array, Array...]
    }
  echo "]</script>";
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kyle Hamilton

ASKER

Thanks again leakim971!

That did the trick.
If you have a comma at the end, use trim($yourString,",") for example.
Also consider using json_encode that transfers your array directly into a javascript object.
As always thanks for your help...
You're welcome, have a nice sunday and a good week!