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

How to delete array elements in a loop in php

青灯夜游
Release: 2023-03-12 21:20:01
Original
2257 people have browsed it

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);
?>
Copy after login

Output result:

How to delete array elements in a loop in php

Description:

foreach ($array as $key => $value){
    语句块;
}
Copy after login
  • 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);
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template