How to use foreach to delete array elements in php

青灯夜游
Release: 2023-03-11 18:46:02
Original
4380 people have browsed it

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

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

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:

";
}
foreach ($array as $key => $value) {
    echo "键名是:" . $key . "值是:" . $value;
    echo "
"; } ?>
Copy after login

The result printed by executing the above code is:

值是:0
值是:1
值是:2
键名是:0值是:0
键名是:1值是:1
键名是:2值是:2
Copy after login

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!

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!