开发者

How to add or remove (if already exists) a key=>value pair to an array?

I would like to do this with a 开发者_如何学JAVAsingle function.

I have a key=>value pair:

14=>1

I have an array containing many such pairs:

array(15=>2, 16=>7, 4=>9)

I want a function which will add the key=>value pair to the array in case it is not already there but it will remove it from the array if it is already there.

I would like to have a single function for this.


function updateArray($array, $findKey, $findValue) {

    foreach($array as $key => $value) {

        if ($key == $findKey AND $value == $findValue) {
            unset($array[$key]);
            return $array;
        }
    }

    $array[$findKey] = $findValue;
    return $array;

}


function add_or_remove(&$array, $key, $value) {

    // remove key/value pairs if they're both identical
    if (array_key_exists($key, $array)
      && $array[$key] == $value) {
        unset($array[$key]);

    // add new key/value pair
    // OR modify the value for existing key
    } else {
        $array[$key] = $value;
    }
}


Sounds homework to me.

function yourSpecialFunctionRenameMe(&$array, $key, $value){
    if(array_key_exists($array, $key) && $array[$key] == $value){
        $array[$key] = $value;
    }else{
        unset($array[$key]);
    }
}


function arr_add_rem($arr, $k, $v){
    if(!array_key_exists($k)){
        $arr[$k] = $v;
    }
    else{
        unset($arr[$k]);
    }

    return $arr;
}

Something like this?


function add_or_remove_key_value_pair(&$array, $key, $value){
    if ($key == array_search($value, $array))
        unset($array[$key]);
    else
        $array[$key] = $value;
}

Test:

$array = array(15=>2, 16=>7, 4=>9);
add_or_remove_key_value_pair($array, 15, 2);// 15=>2 will be removed
add_or_remove_key_value_pair($array, 14, 1);// 14=>1 will be added
var_dump($array);

Output:

array(3) { 
    [16]=> int(7) 
    [4]=> int(9) 
    [14]=> int(1) 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜