Reputation: 422
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.
Upvotes: 0
Views: 67
Reputation: 78994
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.
Upvotes: 0
Reputation: 387
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'
Upvotes: 2