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

青灯夜游
Release: 2023-04-05 12:14:01
Original
4640 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!