PHP: How to identify AND CHANGE duplicate values in an array?

自作多情 提交于 2019-11-30 16:16:22

For the array in your question and for adding numbers at the end if a duplicate, you only need to loop over the array once and temporary build up a helper array that stores if a value has been already found (and how often):

$found = array();

foreach($array as &$value)
{
    if (is_int($value)) continue; # skip integer values

    if (isset($found[$value]))
    {
        $value = sprintf('%s-%d', $value, ++$found[$value]);
    }
    else
    {
        $found[$value] = 0;
    }
}
unset($value);

Demo

First of all, I think you have a rather complicated array structure.

Why don't you change it into something like:

$arr = array(
    '49' => 'big.dup',
    '233' => 'another.duplicate',
    '653' => 'big.dup',
    '387' => 'big.dup',
    '729' => 'another.duplicate',
    '1022' => 'big.dup',
);

This way, you can easily check for duplicate using something like this:

$arr = array(
    '49' => 'big.dup',
    '233' => 'another.duplicate',
    '653' => 'big.dup',
    '387' => 'big.dup',
    '729' => 'another.duplicate',
    '1022' => 'big.dup',
);
$arr_val = array();
foreach( $arr as $key => $val)
{
    if(isset($arr_val[ $val ]))
    {
        $arr_val[ $val ]++;
        $arr[ $key ] = $val . $arr_val[ $val ];
    }
    else
    {
        $arr_val[ $val ] = 0;
    }
}

Or, if you insist on using that complicated array structure, you can modify code above into this:

$arr_val = array();
foreach( $arr as $key => $val)
{
    if(isset($arr_val[ $val ]) && !is_numeric( $val ) )
    {
        $arr_val[ $val ]++;
        $arr[ $key ] = $val . $arr_val[ $val ];
    }
    else
    {
        $arr_val[ $val ] = 0;
    }
}

You may notice that there's not much different here. I just add && !is_numeric($val) to it as I think, you wouldn't want to process the ID. Though, I still think that the ID will never duplicate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!