VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-remove-a-key-and-its-value-from-an-associative-array-in-php/

⇱ How to remove a key and its value from an associative array in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to remove a key and its value from an associative array in PHP ?

Last Updated : 7 Jun, 2024

Given an associative array containing array elements the task is to remove a key and its value from the associative array.

Examples:

Input : array( "name" => "Anand", "roll"=> "1")
Output : Array (
 [roll] => 1
)

Input : array( "1" => "Add", "2" => "Multiply", "3" => "Divide")
Output : Array (
 [2] => Multiply
 [3] => Divide
)

Using unset() function

The unset() function is used to unset a key and its value in an associative array.

Syntax:

void unset( $array_name['key_to_be_removed'] )

Program:


Output
Array
(
 [2] => Multiply
 [3] => Divide
)

Using array_diff_key() function

This function is used to get the difference between one or more arrays. This function compares the keys between one or more arrays and returns the difference between them.

Syntax:

array array_diff_key( $array_name, array_flip((array) ['keys_to_be_removed'] )

Program:


Output
Array
(
 [2] => b
 [3] => c
)

Using array_filter function

The array_filter function can be used to filter elements of an array using a callback function. This approach allows you to remove specific keys by returning false for those keys in the callback function.

Program:


Output
Array
(
 [2] => Multiply
 [3] => Divide
)
Comment
Article Tags: