add to array if it isn't there already

前端 未结 14 1244
北海茫月
北海茫月 2020-12-13 07:53

How do I add elements to an array only if they aren\'t in there already? I have the following:

$a=array();
// organize the array
foreach($array as $k=>$v)         


        
14条回答
  •  自闭症患者
    2020-12-13 08:36

    Since there are a ton of ways to accomplish the desired results and so many people provided !in_array() as an answer, and the OP already mentions the use of array_unique, I would like to provide a couple alternatives.

    Using array_diff (php >= 4.0.1 || 5) you can filter out only the new array values that don't exist. Alternatively you can also compare the keys and values with array_diff_assoc. http://php.net/manual/en/function.array-diff.php

    $currentValues = array(1, 2);
    $newValues = array(1, 3, 1, 4, 2);
    var_dump(array_diff($newValues, $currentValues));
    

    Result:

    Array
    (
        [1] => 3
        [3] => 4
    )
    

    http://ideone.com/SWO3D1

    Another method is using array_flip to assign the values as keys and compare them using isset, which will perform much faster than in_array with large datasets. Again this filters out just the new values that do not already exist in the current values.

    $currentValues = [1, 2];
    $newValues = [1, 3, 1, 4, 2];
    $a = array();
    $checkValues = array_flip($currentValues);
    foreach ($newValues as $v) {
        if (!isset($checkValues[$v])) {
            $a[] = $v;
        }
    }
    

    Result:

    Array
    (
        [0] => 3
        [1] => 4
    )
    

    http://ideone.com/cyRyzN

    With either method you can then use array_merge to append the unique new values to your current values.

    1. http://ideone.com/JCakmR
    2. http://ideone.com/bwTz2u

    Result:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
    )
    

提交回复
热议问题