phparraysloops

Remove zeros that follow a 1 in an array


I am getting the values of an array of checkboxes (created dynamically). There were several issues, but I narrowed it to a certain point. Now the abstract of the problem is this (forget for a second these are checkboxes and just imagine we are working with an array of numbers).

I have an array store[20] which contains values of 0s or 1s. I need to get rid of every 0 that follows a one. Ex. lets assume my array is store={0, 1, 0, 1, 0, 0}. I need to create a new array that will be like this check={0, 1, 1, 0}. The third and fifth terms dont have to be inserted in the new array because they follow the second and fourth term (which are ones).

Also, in case you wonder, there are no occurrences of two consecutive ones, so no need to worry about that.

Here is my php code (but implementations in other languages are the same since its just for loops and arrays):

$j=0;   $count=0;
    for($j=0;$j<20; $j++) {
        $check[$j] = $store[$j + $count];
        if($store[$j]) {
            $count = $count + 1;                
        }
    }

The code is not working correctly. Maybe I am dead wrong in the way im implementing it. But Im a bit tired and started seeing things. I really can't see what im doing wrong.

PS: I didnt include the array declarations and other preceding code because i already tested it and I know they are ok. The problem is in the logic of this part of the code.


Solution

  • Edit: 8 years of experience later, I would simply use a foreach loop on the elements and checking the previous value in the array when you reach a 0. If it's 1, then don't include it in the new array.

    $store = [0, 1, 0, 1, 0, 0];
    $check = [];
    foreach ($store as $index => $value) {
        if ($index > 0 && $value === 0 && $store[$index - 1] === 1) {
            continue;
        }
        $check[] = $value;
    }
    var_dump($check);
    

    This avoids the overhead of converting the values to a string then doing replacements on it before converting it back, it simply creates a new array with the desired elements.

    The original answer is preserved below, but I no longer recommend it.


    In PHP you could just use str_split, a little regex and an implode without having to worry about a for loop. Adding in array_map, the results will be returned as integers instead of strings.

    $check = array_map('intval',str_split(preg_replace('/10/','1',implode('',$store))));
    

    Demo:

    <?php
        $store = array(0, 1, 0, 1, 0, 0);
        $check = str_split(preg_replace('/10/', '1', implode('', $store)));
        var_dump($check);
        $check = array_map('intval', $check);
        var_dump($check);
    ?>