Home >Backend Development >PHP Tutorial >How to use unset() to delete array elements in a foreach loop? (code example)
We can use the unset() function in the foreach loop to delete the specified array element. The following article will take you to understand the unset() function and introduce the unset() function in the foreach loop to delete the specified array element. Method, I hope it will be helpful to everyone.
unset() function: is PHP’s built-in function, used to unregister the specified variable. The behavior of this function depends on different things, if this function is called from inside any user defined function then it will de-initialize the value associated with the variable inside it and initialize it outside it. [Video tutorial recommendation: PHP tutorial]
Basic sentence structure:
unset( $variable )
The following uses code examples to introduce the unset() function to delete specified array elements in a foreach loop. method.
Example 1: One-dimensional array
<?php // 声明数组并初始化它 $Array = array( "PHP", "JavaScript", "Python" ); // 输出数组元素 var_dump($Array); // 在foreach循环中移除指定数组元素 foreach($Array as $k => $val) { if($val == "JavaScript") { unset($Array[$k]); } } // 输出数组元素 var_dump($Array); ?>
Output:
Example 2: Two-dimensional Array
<?php // 声明数组并初始化它 $Array = array( array(0 => 1), array(4 => 10), array(6 => 100) ); // 输出数组元素 var_dump($Array); // 在foreach循环中移除指定数组元素 foreach($Array as $k => $val) { if(key($val) == 4) { unset($Array[$k]); } } // 输出数组元素 var_dump($Array); ?>
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to use unset() to delete array elements in a foreach loop? (code example). For more information, please follow other related articles on the PHP Chinese website!