What does this code do ? I can't understand the while loop mainly ! mainly can't understand $total--
function getNiceFileSize($file, $digits = 2)
{
if(is_file($file)){
$filePath = $file;
if(!realpath($filePath)){
$filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
}
$fileSize = filesize($filePath);
$sizes = array("TB", "GB", "MB", "KB", "B");
$total = count($sizes);
while ($total-- && $fileSize > 1024){
$fileSize /= 1024;
}
return round($fileSize, $digits). " " . $sizes[$total];
}
return false;
}
$total--
is the same as $total -= 1
, which is the same as $total = $total -1
. This is known as the decrement operator. You are probably familiar with the increment operator when looking at for
loops, such as for ($i = 0, $i++, $i < 10)
.
The loop can be rewritten as while ($total = $total -1 && $fileSize > 1024)
, which means "while $total is still a truthy value (in this case, a number > 0) and $fileSize is > 1024".