Jump to content

Using implode() in array to string conversions


anderson_catchme
Go to solution Solved by cyberRobot,

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.

 

 

Link to comment
Share on other sites

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; ?>
Link to comment
Share on other sites

  • Solution

@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. :)

Edited by cyberRobot
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.