Getting to my wits end debugging what seems like a simple issue, and I'm worried that there might be something wrong with this block, that I was overlooking due to it's simplicity:
function sendUploads(array $files)
{
$fileCount = count($files)-1;
$lastFile = false;
foreach ($files as $fileKey => $file) {
if ($fileKey == $fileCount) {
$file = $file . ' is the lastfile';
}
$uploads[] = $file;
}
var_dump($uploads);
}
$files = array('file1', 'file2', 'file3', 'file4', 'file5');
sendUploads($files);
The expected result would be:
array(5) {
[0] =>
string(5) "file1"
[1] =>
string(5) "file2"
[2] =>
string(5) "file3"
[3] =>
string(5) "file4"
[4] =>
string(21) "file5 is the lastfile"
}
But in some edge cases we're seeing this result instead:
array(5) {
[0] =>
string(5) "file1"
[1] =>
string(5) "file2"
[2] =>
string(5) "file3"
[3] =>
string(5) "file4"
[4] =>
string(21) "file5 is the lastfile"
[5] =>
string(21) "file5 is the lastfile"
}
In all my testing I'm getting the first result, but is there a potential situation I'm missing where this function could be causing this issue?
Thanks for your time.
I don't know how these edge cases should be possible. But anyhow you are doing n-1 if
comparisons for one case. Why don't you just end
it and manage it on its own?
function sendUploads(array $files)
{
$length = count($files);
if ($length < 1)
return array();
$uploads = array();
$last = end($files);
for ($i=0; $i<($length-2); $i++) {
$uploads[] = $files[$i];
}
$uploads[] = $last . " is the last file";
return $uploads;
}
A variation on a theme perhaps but it originally seemed overly complicated:
function sendUploads( $files=array() ){
if( empty( $files ) ) return false;
$pop=array_pop( $files );
$uploads=$files;
$uploads[]=$pop.' is the last file';
return $uploads;
}
$files = array('file1', 'file2', 'file3', 'file4', 'file5');
if( !empty( $files ) ) var_dump( sendUploads( $files ) );
The code you've provided would never produce the output you've included. I presume that really your code is a lot more complicated than this and you've trimmed out stuff you think is unnecessary. The problem is probably due to the fact that all arrays in PHP are associative - even when the index is an integer value. It's quite possible to have an array with keys { -1, 0, 1, "banana", 300 }. Expecting such a hash map to have an explicit order seems something of a reach.
The simplest solution I can think of (kingkero's is rather neat) would be:
function sendUploads(array $origfiles)
{
$fileCount = count($files)-1;
$lastFile = false;
$files=array_values($origfiles);
// or if this still causes pain sort(array_values($origfiles))
foreach ($files as $fileKey => $file) {
if ($fileKey == $fileCount) {
$file = $file . ' is the lastfile';
}
$uploads[] = $file;
}
var_dump($uploads);
}