""])"."/> ""])".">
Home > Article > Backend Development > How to delete elements based on key in php array
php method to delete array elements based on key: 1. Use the unset() function, the syntax "unset($array[key value])"; 2. Use the array_diff_key() function, the syntax "array_diff_key($array , [key value=> ""])".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php according to key ( Key name) to delete the array element
Method 1: Use the unset() function to delete the element according to the key name of the array element
<?php header("Content-type:text/html;charset=utf-8"); $array = array('name'=>'apple','age'=>12,'address'=>'ChinaGuangZhou'); var_dump($array); unset($array['name']); var_dump($array); ?>
Method 2: Use the array_diff_key() function to delete elements based on the key name of the array element
If you know the key (key) of the array element you want to delete, you can Use array_diff_key(). You need to enter the key to be deleted in the key value position of the second parameter of the function. The value is not required and can be optional.
<?php header("Content-type:text/html;charset=utf-8"); $array = array('name'=>'apple','age'=>12,'address'=>'ChinaGuangZhou'); var_dump($array); $array = array_diff_key($array, ['age' => ""]); var_dump($array); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete elements based on key in php array. For more information, please follow other related articles on the PHP Chinese website!