Jump to content

Using implode() in array to string conversions


anderson_catchme

Recommended Posts

This is my code for displaying images from a folder:

 

 function generate_img ($imagepointer, $imageornot){
 if($imageornot == 1){
 $var = getcwd();
 $dirlocation = $var."\\imageuploads\\".$imagepointer;
 $files = array_diff(scandir($dirlocation), array('..', '.'));
 foreach ($files as $image){
 $data[] = array('label' => '<img src="/imageuploads/'.$imagepointer.'/'.$image.'" alt="thumbnail"> <br/>');
        };
    return $data;
    }
    else {
    return FALSE;
    }
 }

 

I'm using it with print_r:            

 

<p><?php print_r(generate_img($imagepointer, $imageornot)); ?></p>

 

 

Working ok, but obviously not good for a live site. Is implode() a good idea in this situation? And how would I use it?

Appreciated.

 

 

I think you're asking if there's a cleaner solution as opposed to can you use implode.

 

Personally, I'd store just the URLs and loop with a foreach statement to print them.

 

$dirs = array_diff(scandir($dirlocation), array('..', '.'));
array_walk($dirs, function(&$v, $k, $d) {
   $v = $d . $v;
}, $dirlocation); 

// HTML section
<?php foreach($dirs as $url) : ?>
// IMG tag with SRC = $url
<?php endforeach; ?>

@anderson_catchme - Do you need the associative array for the function output? If not, you could change this:

$data[] = array('label' => '<img src="/imageuploads/'.$imagepointer.'/'.$image.'" alt="thumbnail"> <br/>');

To this:

$data[] = '<img src="/imageuploads/'.$imagepointer.'/'.$image.'" alt="thumbnail"> <br/>';

And then use implode() here:

<p><?php echo implode(generate_img($imagepointer, $imageornot)); ?></p>

Edit: sorry I forgot the to add "echo" before the implode() function. I guess I'm not quite awake yet. :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.