dongzexi5125 2018-06-12 09:44
浏览 126
已采纳

从数组PHP中删除相邻的重复项会忽略值为0的第一个元素

I have following code to remove adjacent duplicates from an array

$myArray = array(
                    0 => 0,
                    1 => 0,
                    2 => 1,
                    5 => 1,
                    6 => 2,
                    7 => 0,
                    8 => 0,
                );

            $previtem= NULL;
            $newArray = array_filter(
                $myArray,
                function ($currentItem) use (&$previtem) {
                    $p = $previtem;
                    $previtem= $currentItem;
                    return $currentItem!= $p ;
                }
            );

echo "<pre>";
print_r($newArray);

Problem

Required Output.

Array
(
    [0] => 0
    [2] => 1
    [6] => 2
    [7] => 0
)

Actual output

Array
(
    [2] => 1
    [6] => 2
    [7] => 0
)

How to get required output without modifying my code much?? or is there any other better way?

Thanks

  • 写回答

1条回答 默认 最新

  • douyi1939 2018-06-12 09:48
    关注

    The problem is the loose comparison in your filter function. When you say

    return $currentItem != $p ;
    

    PHP is treating the initial null value of $p and the 0 value of $currentItem as equivalent, so the first iteration gets filtered out.

    If you change the line to use strict comparison instead (=== or !==), it will work as expected

    return $currentItem !== $p ;
    

    This ensures only adjacent values that are exactly the same, including type comparison, are filtered.

    See https://eval.in/1019471

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?