PHP is a widely used programming language and one of the most popular languages for web development. The PHP function library provides a variety of functions, among which the in_array() function is a very useful function. This article will introduce in detail how to use the PHP in_array() function.
The in_array() function is used to find a specific value in an array. This function returns true if the specified value is found, otherwise it returns false.
The function syntax is as follows:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Parameter $needle: the value to be found, Can be any data type
Parameter $haystack: the array to be searched
Parameter $strict: optional parameter, the default is false, indicating non-strict mode. If set to true, the data type will be compared in addition to the value
Returns true if $needle exists in the $haystack array. If not found, returns false.
The following are several examples of using the PHP in_array() function:
(1) Find a string
$fruits = array("apple", "banana", "orange", "grape");
if (in_array("banana", $fruits)) {
echo "Found banana";
}
The above code first defines an array containing several fruits, and then uses the in_array() function to check whether it contains the string "banana". If included, "banana found" will be output.
(2) Find numbers
$numbers = array(1, 3, 5, 7, 9);
if (in_array(5, $numbers)) {
echo "Found 5";
}
Similar to the above code, an array is defined here containing several numbers. Then use the in_array() function to find the number 5.
(3) Use strict parameter
$cars = array("Volvo", "BMW", "Toyota");
if (in_array("1", $cars, true)) {
echo "1 found";
} else {
echo "1 not found";
}
In the above code, we used in_array ()The third parameter of the function is the $strict parameter. This means that in addition to matching values, data types are also compared. So if the array contains the string "1" and you are searching for the number 1, there will be no match.
PHP in_array() function is a powerful and convenient tool for finding specific values in an array. It accepts multiple data types and can use strict comparisons. You can use this function to check if a value exists in an array to make it easier to do conditional statements and logical operations while writing PHP code.
The above is the detailed content of Introduction to the use of PHP in_array() in the function library. For more information, please follow other related articles on the PHP Chinese website!