""])"."/> ""])".">

Home  >  Article  >  Backend Development  >  How to delete elements based on key in php array

How to delete elements based on key in php array

青灯夜游
青灯夜游Original
2022-03-10 16:50:252700browse

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=> ""])".

How to delete elements based on key in php array

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(&#39;name&#39;=>&#39;apple&#39;,&#39;age&#39;=>12,&#39;address&#39;=>&#39;ChinaGuangZhou&#39;);
var_dump($array);

unset($array[&#39;name&#39;]);
var_dump($array);
?>

How to delete elements based on key in php 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(&#39;name&#39;=>&#39;apple&#39;,&#39;age&#39;=>12,&#39;address&#39;=>&#39;ChinaGuangZhou&#39;);
var_dump($array);

$array = array_diff_key($array, [&#39;age&#39; => ""]);
var_dump($array);
?>

How to delete elements based on key in php 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn