How to Remove a Key and its Value From an Associative Array In PHP

admin_img Posted By Bajarangi soft , Posted On 03-12-2020

Given an associative array containing array elements and the task is to remove a key and its value from the associative array,The unset() function is used to unset a key and its value in an associative array, 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.

associative array in php

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'] )
Code:

<?php

$arr=array("1"=>"add","2"=>"multiply","3"=>"division");

unset($arr['1']);

print_r($arr);

?>

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'] )
Code :

<?php

$arr=array("1"=>"a","2"=>"b","3"=>"c");

$result=array_diff_key($arr,array_flip((array)['1']));

print_r($result);

?>

Related Post