"b", 2 => "c"); unset($ array[1]);]."/> "b", 2 => "c"); unset($ array[1]);].">

Home  >  Article  >  Backend Development  >  How to clear array elements in php

How to clear array elements in php

王林
王林Original
2020-11-02 09:38:111815browse

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:

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

Output result:

Array (
    [0] => a    
    [2] => c
)

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().

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

Output results:

Array(
    [1] => b
)

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!

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