2

A folder on my server holds a variable number of images. I'm working on a PHP script that is intended to retrieve the entire list of files there (a list of filenames) and create an associative array like so:

$list = array(1=>"image1.png", 2=>"image2.png", ...);

Basically, the list vector starts as empty and when a new image is found, its name has to be added to the list, with an incremented index: i=>"image[i].png"

How do I go about achieving this? Or in other words, how do I push a new element to my array?

3 Answers 3

2

I'm not sure why you are referring to this as an associative-array, but if you want to add somethign to an array, do it like this

   $list = array();
   $list[] = "image1.png";
   $list[] = ....;
   $list[] = "imagei.png";
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to push new item to your array, try with:

$list[] = "image" + ( count($list) + 1 ) + ".png";

If your items' indexes starts with 1, add +1 in the name as described above. If you are starting from 0 as it is natural behaviour, skip it and use as described below:

 $list[] = "image" + count($list) + ".png";

Comments

0

So you are in fact re-implementing glob()?

$list = glob('/path/to/images/*.png');

If you are really want to reimplement it yourself

$i = 0;
$list = array();
while (file_exists('/path/to/image' . (++$i) . '.png'))
  $list[$i] = "image$i.png";

2 Comments

@Matt No, php.net has a bad day. Just push F5 for a while ;)
add www... php.net is broken today

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.