0

I have an array where there is a key and a value. I generate it by cycling through an image folder:

$images = array(); 
foreach (glob("images/myimages/*.{png,jpg,jpeg,JPG}", GLOB_BRACE) as $filename) {  
    $images[$filename] = filemtime($filename); 
}

arsort($images); 

$newest = array_slice($images, 0, 5);

This gives me the following array:

images/myimages/image1.jpg => 1472497034
images/myimages/IMG_02.JPG => 2347389498
images/myimages/DSC_0066.png => 7837392948
images/myimages/fred_bloggs.jpg => 1472497034
images/myimages/IMG4532.JPG => 2347389498

I want to extract each key from the $newest array into a new variable so image1.jpg becomes $var1, IMG_02.JPG becomes $var2 etc.

I have 2 problems. First, the filename needs the "images/myimages/" pathname stripping from it (and a check whether files exist in that folder). Second, I can't see how to extract the 5 keys into those 5 new variables. All the examples I see extract the key into a variable of the same name such as here http://php.net/manual/en/function.extract.php

How can I achieve this?

Thanks in advance.

4
  • 3
    Why extract to vars? Just use $newest = array_keys($newest); and then echo $newest[0]; etc... Or loop thru it. Also see basename(). Commented Sep 26, 2016 at 19:30
  • 3
    You almost never want variables like $var1, $var2, etc. Whenever you're doing that, you should just use an array. Commented Sep 26, 2016 at 19:31
  • 1
    As said in the previous comments, better use an array than $varX, but FYI, you can have a look at php.net/manual/fr/function.list.php Commented Sep 26, 2016 at 19:35
  • @AbraCadaver - Nice answer that simplifies what I want to achieve. Commented Sep 27, 2016 at 16:51

2 Answers 2

2

Really I dont understand why you need that. But you could do something like this:

$prefix = 'var'; $count = 0;
foreach($newest as $key => $value) {
   $count++;
   ${$prefix.$count} = $key;
}

echo $var1; // 'images/myimages/image1.jpg'
Sign up to request clarification or add additional context in comments.

Comments

0

You will be better off just using an array:

$newest = array_keys($newest);

Then access 0-4:

echo $newest[0];

To get just the filename:

$newest = array_map('basename', $newest);

Or you can just use basename() when creating your original array.

Comments

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.