$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 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])".
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:
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('a' => array('a1', 'a2'), 'b' => array('b1', 'b2')); foreach ($array as $key => $value) { if ($key == 'a') { unset($array[$key]); } //或者删除二维数组中二维中的元素 if ($key == 'a') { 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!