$value){}"; 2. Use the unset() function in the loop body to delete the array elements, the syntax "unset($array[$key])"."/> $value){}"; 2. Use the unset() function in the loop body to delete the array elements, the syntax "unset($array[$key])".">

Home  >  Article  >  Backend Development  >  How to delete array elements in a loop in php

How to delete array elements in a loop in php

青灯夜游
青灯夜游Original
2021-09-23 19:29:382202browse

How to loop through the array elements: 1. Use the foreach statement to loop through the array, the syntax is "foreach($array as $key=>$value){}"; 2. Use unset( in the loop body ) function deletes array elements, the syntax is "unset($array[$key])".

How to delete array elements in a loop in php

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

php loop to delete array elements

In PHP, you can use the foreach statement and the unset() function to loop through array elements.

<?php
header("Content-type:text/html;charset=utf-8");
$array = array("香蕉", "苹果", "梨子", "橙子", "橘子", "榴莲");
foreach ($array as $key => $value) {
	unset($array[$key]);
}
var_dump($array);
?>

Output result:

How to delete array elements in a loop in php

Description:

foreach ($array as $key => $value){
    语句块;
}
  • Traverse the given $array array , in each loop, the value of the current array will be assigned to $value, and the key name will be assigned to $key.

The unset() function is used to destroy the given variable.

If you don’t want to delete all elements, but only want to delete specified elements, you can add an if statement for judgment

<?php
header("Content-type:text/html;charset=utf-8");
$array = array(&#39;a&#39; => array(&#39;a1&#39;, &#39;a2&#39;), &#39;b&#39; => array(&#39;b1&#39;, &#39;b2&#39;));
foreach ($array as $key => $value) {
	if ($key == &#39;a&#39;) {
		unset($array[$key]);
	}
	//或者删除二维数组中二维中的元素
	if ($key == &#39;a&#39;) {
		unset($array[$key][0]);
	}
}
var_dump($array);
?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete array elements in a loop in php. 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