$v){if($v==' value '){unset($array[$k])}"."/> $v){if($v==' value '){unset($array[$k])}".">

Home  >  Article  >  Backend Development  >  How to use foreach to delete array elements in php

How to use foreach to delete array elements in php

青灯夜游
青灯夜游Original
2021-07-22 19:00:274555browse

Method: First use the foreach loop structure to traverse the array; then use the unset() function in the loop body to delete the specified array value, the syntax is "foreach($array as $k=>$v){if ($v=='value'){unset($array[$k])}".

How to use foreach to delete array elements in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Use the foreach and unset() functions Delete specific elements in the array

foreach($array as $k=>$v){
if($v == 'day'){
unset($array[$k]);
}
}

unset() function deletes the specified array value.

Introduction to foreach loop structure

The foreach loop structure is a commonly used method when traversing arrays. foreach can only be applied to arrays and objects. If you try to apply it to other data types Variables or uninitialized variables will issue an error message.

foreach has the following two syntax formats:

//格式1
foreach (array_expression as $value){
    statement
}
//格式2
foreach (array_expression as $key => $value){
    statement
}

When the first format traverses the array_expression array, each loop assigns the value of the array to $value; the second traversal not only assigns the array value Assign to $value and assign the key name to $key.

An example demonstrates the difference between the two formats:

<?php
$array = [0, 1, 2];
foreach ($array as $val){
    echo "值是:" . $val ;
    echo "<br/>";
}
foreach ($array as $key => $value) {
    echo "键名是:" . $key . "值是:" . $value;
    echo "<br/>";
}
?>

The result printed by executing the above code is:

值是:0
值是:1
值是:2
键名是:0值是:0
键名是:1值是:1
键名是:2值是:2

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to use foreach to delete array elements in php. 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