Home  >  Article  >  Backend Development  >  How to remove specified value from php array

How to remove specified value from php array

青灯夜游
青灯夜游Original
2021-06-04 19:16:082219browse

Method: 1. First use the foreach statement to traverse the array and find the subscript corresponding to the specified value; then use the "unset(arr[subscript])" statement to delete; 2. First use the array_search() function to Search for a specific value in the array and return the corresponding key name; then use the unset() function to delete the element based on the key name.

How to remove specified value from php array

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

Method 1: Using foreach and unset () function deletes a specific element in the array

public static function delByValue(&$arr, $value){
        if(!is_array($arr)){
            return $arr;
        }
        foreach($arr as $k=>$v){
            if($v == $value){
                unset($arr[$k]);
            }
        }
        return true;
    }

unset() function is used to destroy the given variable.

Method 2: Use the array_search() and unset() functions to delete specific values ​​in the array

First use the array_search() function to search for specific values ​​in the array and return The corresponding key name; then use the unset() function to delete the element based on the key name.

if(($key = array_search('day',$arr))){
unset($arr[$key]);
}

array_search() function searches for a key value in the array; if the value is found, the key name of the matching element will be returned; if not found, false is returned.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove specified value from php array. 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