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

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器