krikkaa krikkaa - 1 month ago 23
PHP Question

Replace values in array with surrounding null,0

So I have a collection of integer values, which is built from a result of another function that can have different values every time. Consider the following in PHP:

$arr = [0,0,2,2,0,0,0,3,3];


Which i need to convert to:

$newArr = [null,0,2,2,0,null,0,3,3];


What i want to accomplish is: If a value is > 0, its neighbours should be 0, and the rest should be null.

What is the best strategy here?

Answer

Playing with operator precedence:

$zero = true;

$arr = [0,0,2,2,0,0,0,3,3];
$newArr = [];

foreach($arr as $k=>$v) {
    if ($v) {
        $newArr[] = $v;
        $zero = false;
    } else {
        if ($zero and isset($arr[$k+1]) && !$arr[$k+1] || !isset($arr[$k+1]))
            $newArr[] = null;
        else
            $newArr[] = 0;

        $zero = true;
    }
}

print_r($newArr);