Home > Backend Development > PHP Problem > How to clear array elements in php

How to clear array elements in php

王林
Release: 2023-03-06 22:04:02
Original
2004 people have browsed it

php method to clear array elements: You can use the unset() function to clear array elements, such as [$array = array(0 => "a", 1 => "b", 2 => ; "c"); unset($array[1]);].

How to clear array elements in php

#If you want to delete an element in the array, you can use the unset() method.

(Video tutorial recommendation: php video tutorial)

unset() method

Note that if you use the unset() method, it will not Change other keys.

Example:

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
unset($array[1]);
//↑ 你要删除的数组元素值的键
print_r($array);
?>
Copy after login

Output result:

Array (
    [0] => a    
    [2] => c
)
Copy after login

If you want to delete multiple elements in the array, you cannot use the unset() function. , you need to use the array_diff() method, which requires knowing the key or value to be deleted.

array_diff() method

If you know the array element you want to delete, you can use array_diff().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff($array, ["a", "c"]);
//└────────┘→你要删除的元素
print_r($array );
?>
Copy after login

Output results:

Array(
    [1] => b
)
Copy after login

Related recommendations: php training

The above is the detailed content of How to clear 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