Home >Backend Development >PHP Tutorial >How to use unset() to delete array elements in a foreach loop? (code example)

How to use unset() to delete array elements in a foreach loop? (code example)

青灯夜游
青灯夜游Original
2019-02-26 15:20:364701browse

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.

How to use unset() to delete array elements in a foreach loop? (code example)

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:

How to use unset() to delete array elements in a foreach loop? (code example)

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:

How to use unset() to delete array elements in a foreach loop? (code example)

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!

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

Related articles

See more