Lunatic Fnatic Lunatic Fnatic - 2 months ago 11
PHP Question

How to get highest number while in foreach loop

I have a function that returns mp3 list with its qualities. I want to return HD value true if I reach the last element in the array but i have a problem in foreach loop. It always returns true.

Code

function funcName() {
foreach($dirs as $d) {
if (filesize($d) > 200) {
$qualities = substr(strrchr(basename($d), "-"), 1);
$qualities = preg_replace('/\\.[^.\\s]{3,4}$/', '', $qualities);
// This is where I check whether it is the last element or not.
$numItems = count($dirs);
$i = 0;
foreach($dirs as $key => $value) {
if (++$i === $numItems) {
$zaa = true;
} else {
$zaa = false;
}
}
$files[] = ["files" => basename($d), "qualities" => $qualities, "hd" => $zaa];
}
}
return ($files);
}


I just want to return
$zaa = true
if I reach to the last element. In my code, it returns true all the time.

Could you please show me in whic part am I failing?

Answer

I guess this should work:

function funcName() {

$numItems = count($dirs);
$i = 0;
foreach($dirs as $d) {
$i++;
    if (filesize($d) > 200) {
        $qualities = substr(strrchr(basename($d), "-"), 1);
        $qualities = preg_replace('/\\.[^.\\s]{3,4}$/', '', $qualities);         
        if ($i == $numItems) {
            $zaa = true;
        } else {
            $zaa = false;
        }            
        $files[] = ["files" => basename($d), "qualities" => $qualities, "hd" => $zaa];
    }
}
return ($files);
}