Change language

How can I remove a key and its value from an 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 the unset() function:The unset() function is used to reset the key and its value in an associative array.Syntax:
void unset ($array_name [’key_to_be_removed’])
Program:  
// Declare an associative array $arr = array ( "1" = > "Add" , "2" = > "Multiply" , "3" = > "Divide");  
// Remove key 1 and its value
// from associative array unset ( $arr [ ’1’ ]);  
// Show array elements print_r ( $arr );  
?>
Exit:
Array ([ 2] = > Multiply [3] = > Divide)
Method 2: Using the function array_diff_key ( ) :this function is used to get the difference between one or more arrays. This function compares 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:  
// Declare an associative array $arr = array ( "1" = > "a" , "2" = > "b" , "3" = > "c");  
// Remove key 1 and its value
// from associative array $result = array_diff_key ( $arr , array_flip (( array ) [ ’1’ ]));  
// Show result print_r ( $result );  
?>
Exit:
Array ([ 2] = > b [3] = > c)

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method