2

I'm using this php code to get all the images from a folder and put all the results in an array:

<?php

$images = [];
$dir    = 'images/*';
$file = glob($dir);

for ($x = 0; $x < count($file); $x++) {
          $images[] = [ $file[$x] => $x];
}

print_r($images);

?>

Where i'm getting my results stored in the "$images" array:

print_r($images);
Output : /*Array ( [0] => Array ( [images/1.jpg] => 0 ) [1] => Array ( [images/2.jpg] => 1 ) [2] => Array ( [images/3.jpg] => 2 ) )*/

Now, i want to get the first value of the array in a string format, "images/1.jpg" i tried to print it out using its index but it displays the key and the word array in the beginning:

print_r($images[0]);
Output : /*Array ( [images/1.jpg] => 0 )*/

How to get only this value : "images/1.jpg" ?

Thanks.

3
  • That's it. Do echo($images[0]); ... The command print_r add additional info. The command echo will just output the value. Commented Oct 24, 2018 at 22:57
  • 1
    @Daniel you can’t just echo an array. Commented Oct 24, 2018 at 22:58
  • 2
    @EdCottrell - Ah... you're of course correct. There is a little more complexity here with being multi-dimensional .. Commented Oct 25, 2018 at 15:22

3 Answers 3

2

You should use foreach to iterate through collections.

foreach (array_expression as $key => $value)
    statement

foreach (array_expression as $value)
    statement

In your case this would be

foreach (glob($dir) as $filename) {
    print_r($filename);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could help ;-)
1

You have a nested array, and the keys of the inner array (not the values) contain the image names. So, you need to reference it like this:

$names = array_keys($images[0]);
print_r($names[0]);

1 Comment

Yes, you're right, thank you very much for your answer.
-2

You have to change the for loop to tgis:

for ($x = 0; $x < count($file); $x++) { 
{
$images[x] = [$file[$x]];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.