Fill an array with last non-zero element to the end in PHP I need to fill an array with the last non-zero value.

Points of note I guess are that the array will either have all 0 values or end with 0 values.

Please review my code below.

&lt;?php

$array = [1, 1, 5, 4, 0, 0];
$array2 = [0, 0, 0, 0, 0, 0];


function padArray($array) {
    $length = count($array) - 1;
    for ($i = $length; $i &gt;= 0; $i--) {
        if($array[$i] != 0) {
            for ($j = $i; $j &lt; count($array); $j++) {
                $array[$j] = $array[$i];
            }
            break;
        }
    }
    return $array;
}


var_dump(padArray($array));
var_dump(padArray($array2));

//should output [1,1,5,4,4,4]
//should output [0,0,0,0,0,0]
Do you really want this function to use loose comparison $array[$i] != 0?  What should intended behavior be for other potentially falsey values at the end of the array (false, "", [], etc.)?  If you truly only want to replace only trailing zeroes, then you must use exact comparison here !==.
Your function name seems unclear with regards to what the function does.  Perhaps arrayPadOverTrailingZeroes, arrayPadOverTrailingEmptyValues (depending on desired behavior).
PHP provides built-in array functions that may clean up this code a little bit (and perhaps perform slightly better since they are compiled).


For example:

function arrayPadOverTrailingZeroes($array) {
    $length = count($array);
    while (($value = end($array)) === 0) {
        array_pop($array);
    }
    // This conditional to support case where you have all zeroes,
    // in which case, the while loop above would have discarded all array members
    // and $value would be set to false
    if (count($array) === 0) {
        $value = 0;
    }
    return array_pad($array, $length, $value);
}


Answered this before I saw your all-zeroes use case.  Added some additional logic above to handle this case.