简体   繁体   中英

How can I remove a key and its value from an associative array?

Given an associative array:

array("key1" => "value1", "key2" => "value2", ...)

How would I go about removing a certain key-value pair, given the key?

You can use unset :

unset($array['key-here']);

Example:

$array = array("key1" => "value1", "key2" => "value2");
print_r($array);

unset($array['key1']);
print_r($array);

unset($array['key2']);
print_r($array);

Output:

Array
(
    [key1] => value1
    [key2] => value2
)
Array
(
    [key2] => value2
)
Array
(
)

使用unset()

unset($array['key1']);

Use this function to remove specific arrays of keys without modifying the original array:

function array_except($array, $keys) {
  return array_diff_key($array, array_flip((array) $keys));   
} 

First param pass all array, second param set array of keys to remove.

For example:

$array = [
    'color' => 'red', 
    'age' => '130', 
    'fixed' => true
];
$output = array_except($array, ['color', 'fixed']);
// $output now contains ['age' => '130']

使用未unset

unset($array['key1'])

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key :

     // To unset an element from array using Key: unset($arr["key2"]); var_dump($arr); // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
  • To remove element by value :

     // remove an element by value: $arr = array_diff($arr, ["value1"]); var_dump($arr); // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index :

     array_splice($arr, 1, 1); var_dump($arr); // array(1) { ["key3"]=> string(6) "value3" }

read more about array_splice: http://php.net/manual/en/function.array-splice.php

You may need two or more loops depending on your array:

$arr[$key1][$key2][$key3]=$value1; // ....etc

foreach ($arr as $key1 => $values) {
  foreach ($key1 as $key2 => $value) {
  unset($arr[$key1][$key2]);
  }
}

you can do it using Laravel helpers :

first helper, method Arr::except :

$array = ['name' => 'Desk', 'price' => 100];

$filtered = Arr::except($array, ['price']);

// ['name' => 'Desk']

second helper: method Arr::pull

$array = ['name' => 'Desk', 'price' => 100];

$name = Arr::pull($array, 'name');

// $name: Desk

// $array: ['price' => 100]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM