Reputation: 161
I am working with copying files, I can copy one file to multi folders, but I have problem when copying multi files to multi folders.
My code :
$sourcefiles = array('./folder1/test.txt', './folder1/test2.txt');
$destinations = array('./folder2/test.txt', './folder2/test2.txt');
//do copy
foreach($sourcefiles as $source) {
foreach($destinations as $des){
copy($source, $des);
}
}
But this code not work !
Could you give me a solution :(
Thanks for any help !
Upvotes: 0
Views: 353
Reputation: 4371
What you currently do is looping the sourcefiles, which in the first itteration is "test.txt" and then you loop the destination array and performing the copy function 2 times:
1st iteration with folder1/test.txt
2nd iteration with folder1/test2.txt:
In the end you've overwritten both files with the last file in your $source array. So both files in "folder2" contain the data of test2.txt
What you are looking for would be:
foreach($sourcefiles as $key => $sourcefile) {
copy($sourcefile, $destinations[$key]);
}
$sourcefile equals $sourcefiles[$key] in the above example.
This is based on the fact that PHP automatically assigns keys to your values. $sourcefiles = array('file1.txt', 'file2.txt'); can be used as:
$sourcefiles = array(
0 => 'file1.txt',
1 => 'file2.txt'
);
Another option is to use the length of one of the arrays in a for loop, which does the same thing but in a different way:
for ($i = 0; $i < count($sourcefiles); $i++) {
copy($sourcefiles[$i], $destinations[$i]);
}
Upvotes: 5
Reputation: 3127
Of course not. Your nested loop is copying the files in such a way that they're bound to overwrite previous file copies. I think you need to use a simpler solution. Copying in a nested loop doesn't make any sense.
If you have the source and destination files, then I suggest a single loop:
$copyArray = array(
array('source' => './folder1/test.txt', 'destination' => './folder2/test.txt'),
array('source' => './folder1/test.txt', 'destination' => './folder2/test.txt'));
foreach ($copyArray as $copyInstructions)
{
copy($copyInstructions['source'], $copyInstructions['destination']);
}
But make sure your destination file-names are different!
Upvotes: 0
Reputation: 175098
Since you need the same index for both arrays, use a for
loop.
for ($i = 0; $i < count($sourcefiles); $i++) {
//In here, $sourcefiles[$i] is the source, and $destinations[$i] is the destination.
}
Upvotes: 1
Reputation: 2161
Assuming you have equal amount of files:
// php 5.4, lower version users should replace [] with array()
$sources = ['s1', 's2'];
$destinations = ['d1', 'd2'];
$copy = [];
foreach($sources as $index => $file) $copy[$file] = $destinations[$index];
foreach($copy as $source => $destination) copy($source, $destination);
Upvotes: 1
Reputation: 2068
I think what you're trying to do is this;
for ($i = 0; $i < count($sourcefiles); $i++) {
copy($sourcefiles[$i], $destinations[$i]);
}
You current code will overwrite previous copies.
Upvotes: 1