Home >Backend Development >PHP Problem >How to check if value is in array in php
PHP is a powerful programming language with many built-in functions that make it easier for developers to write code. One of the built-in functions is a function that checks whether a value is in an array. In PHP, this function is called the in_array() function.
The in_array() function is an important array function in PHP. It is used to check whether a value is in an array. Its syntax is as follows:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
The parameters of the in_array() function are as follows:
The following is a simple example showing how to use the in_array() function to check whether a value is in an array:
$fruits = array("apple", "banana", "orange", "kiwi"); if (in_array("apple", $fruits)) { echo "Found"; } else { echo "Not found"; }
In this example, we create a file named array of $fruits and checks if it contains an element named "apple". Since the array does contain "apple", the code will print "Found", otherwise it will print "Not found".
Another example showing how to use the in_array() function to check if a value is in an array and remove the value from the array:
$fruits = array("apple", "banana", "orange", "kiwi"); if (in_array("kiwi", $fruits)) { echo "Found"; unset($fruits[array_search("kiwi", $fruits)]); } else { echo "Not found"; } print_r($fruits);
In this example, we check the array Whether $fruits contains an element named "kiwi". Since the array does contain "kiwi", the code will output "Found" and use the unset() function to remove it from the array. Finally, we use the print_r() function to print the contents of the $fruits array.
Summary:
In PHP, you can easily check if a value is in an array using the in_array() function and take appropriate action. This function helps us write code faster and manage data efficiently.
The above is the detailed content of How to check if value is in array in php. For more information, please follow other related articles on the PHP Chinese website!