Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

I would like to do this with a single 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.

like image 271
Richard Knop Avatar asked Nov 24 '10 12:11

Richard Knop


People also ask

Can array have key value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

How do you remove a key value pair from an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

How do you add a key value pair to an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.


1 Answers

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;

}
like image 144
alex Avatar answered Oct 26 '22 22:10

alex