Reputation: 596
I have this array of pictures:
array(3) { [0]=> string(15) "./images/00.jpg" [1]=> string(18) "./images/green.png" [2]=> string(18) "./images/image.png" } string(27) "./images/03/./images/00.jpg"
The number of pictures and of course the names will vary at any time, as there will be constant deleted/added new pictures.
And I use this foreach to loop on all the names:
foreach($images as $image){
$dest = $dest."/".$image;
copy($image, $dest);
unlink($image);
}
in the $images var I store my images names array (listed above).
and in the $dest I have:
$dest = "./images/".$month;
$month = date("m");
The $image var is taking good values (taking each picture one by one full path ex: ./images/00.jpg), but problem is with my $dest var I will get
./images/03/./images/00.jpg //first iteration
./images/03/./images/00.jpg/./images/green.png //second iteration
./images/03/./images/00.jpg/./images/green.png/./images/image.png //third
What I want to do is to get in the $dest only the:
./images/03/00.jpg
./images/03/green.png
./images/03/image.png
1 value/ iteration.
Upvotes: 0
Views: 573
Reputation: 2943
$dest = $dest."/".$image;
In above statement it will work first time fine next time its not initialising $dest
variable again it will take the previous value.
So, you can do the same in other way like below.
foreach($images as $image){
$img_name = explode('/', $image);
$dest = "./images/". date("m") ."/".$img_name[2]; // ./images/03/00.jpg
copy($image, $dest);
unlink($image);
}
Upvotes: 1
Reputation: 595
Why did you concate $dest variable .That is what it's return that the following result
./images/03/./images/00.jpg //first iteration
./images/03/./images/00.jpg/./images/green.png //second iteration
./images/03/./images/00.jpg/./images/green.png/./images/image.png //third
You can use pathinfo()
function to do what you want . Have a look below...
$month=date('m');
foreach($images as $image){
$image_details=pathinfo($image);//The pathinfo() function returns an array that contains information about a path.
$dest = $image_details['dirname']."/".$month."/".$image_details['basename'];
copy($image, $dest);
unlink($image);
}
Upvotes: 1
Reputation: 11631
You have to reinitialize your $dest variable in each iteration.
This should work :
foreach($images as $image){
$dest = "./images/".$month."/".substr($image,strlen("./images/"));
copy($image, $dest);
unlink($image);
}
Update : Use substr on your $image var to get only the part of the string that you are interested in. See the doc for more informations.
Upvotes: 1