krikkaa krikkaa - 1 year ago 106
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 Source

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;
            $newArr[] = 0;

        $zero = true;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download