Thursday, September 4, 2025
HomeLanguagesHow to remove a key and its value from an associative array...

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

Given an associative array containing array elements and 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
)

Method 1: 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:




<?php
  
// Declare an associative array
$arr = array
    "1" => "Add",
    "2" => "Multiply",
    "3" => "Divide"
);
  
// Remove the key 1 and its value
// from associative array
unset($arr['1']);
  
// Display the array elements
print_r($arr);
  
?>


Output:

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

Method 2: 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:




<?php
  
// Declare an associative array
$arr = array
    "1" => "a",
    "2" => "b",
    "3" => "c"
);
  
// Remove the key 1 and its value
// from associative array
$result = array_diff_key($arr
            array_flip((array) ['1']));
  
// Display the result
print_r($result);
  
?>


Output:

Array
(
    [2] => b
    [3] => c
)
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS