Home > Article > Backend Development > How to determine whether a number is in an array in php
In web development, it is often necessary to operate on some arrays. One common operation is to find whether an array contains an element. In PHP, use the in_array() function to determine whether an element is in an array.
The basic syntax of the in_array() function is as follows:
in_array($needle, $haystack);
Among them, $needle is the element to be found, and $haystack is the array to be found. The return value is a Boolean value representing the query result. Returns true if the element exists in the array; otherwise returns false.
The following is an example to demonstrate how to use the in_array() function.
$fruits = array("apple", "banana", "orange", "pear", "grape"); if (in_array("orange", $fruits)) { echo "orange is in the fruits array."; } else { echo "orange is not in the fruits array."; }
The output result is:
orange is in the fruits array.
Here, a fruit array $fruits is first defined, and then the in_array() function is used to query whether "orange" is in the $fruits array. Since "orange" does exist in the array, the query result is true.
In addition to the basic usage, the in_array() function also has some points that we need to pay attention to:
in_array("orange", $fruits, true); //不区分大小写查找
This will find all elements in the array that match "orange" case-insensitively .
To sum up, using the in_array() function can easily determine whether a number is in an array. In actual programming, we can use this function to quickly retrieve the required elements and perform corresponding operations.
The above is the detailed content of How to determine whether a number is in an array in php. For more information, please follow other related articles on the PHP Chinese website!