How to delete based on array value in php

PHPz
Release: 2023-04-10 15:02:17
Original
649 people have browsed it

In PHP, there are usually two ways to delete array elements: deleting based on the array key name and deleting based on the array value. This article will discuss how to delete based on array values.

In PHP, we can use the array_search() function to search for a specified value in an array. The syntax of this function is as follows:

array_search($needle,$haystack,$strict)
Copy after login

The $needle parameter is the value of the element to be found, the $haystack parameter is the array to be searched, and the $strict parameter specifies whether to enable strict mode when searching. This function will search for the $needle element in the $haystack array, and if found, returns the key name of the element in the array, otherwise it returns false.

We can use the array_search() function to find the element to be deleted in the array, and use the unset() function to delete it from the array. The unset() function is used to release the memory space of the specified variable. The syntax of this function is as follows:

unset($var1,$var2,...)
Copy after login

We can pass the searched key name as a parameter to the unset() function, and then delete the element from the array.

Here is an example that demonstrates how to delete elements based on array values:

$fruits = array("apple", "banana", "orange", "grape");

$index = array_search("banana", $fruits);

if($index !== false){
    unset($fruits[$index]);
}

print_r($fruits);
Copy after login

Output:

Array
(
    [0] => apple
    [2] => orange
    [3] => grape
)
Copy after login

In the above example, we created an array containing four fruits array. Then, we use the array_search() function to find the element with the value "banana" and get its key name. Finally, we remove the element using the unset() function.

Summary: In PHP, use the array_search() function to find a specified value in an array. If found, the element can be removed from the array using the unset() function.

The above is the detailed content of How to delete based on array value in php. For more information, please follow other related articles on the PHP Chinese website!

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!