Home > Article > Backend Development > PHP common function analysis: in_array()
In PHP, the in_array() function is a very commonly used function, which can determine whether a value exists in an array. In this article, we will provide an in-depth analysis of the in_array() function.
The syntax of the in_array() function is as follows:
bool in_array(mixed $needle, array $haystack[, bool $strict = FALSE])
where $needle is The value to retrieve, $haystack is the target array, $strict indicates whether to use strict mode (that is, whether to consider types), the default is FALSE.
Next, let’s take a look at an example:
$fruits = array("apple", "banana", "orange"); if (in_array("apple", $fruits)) { echo "有苹果哦!"; }
The output of this code will be “There are apples!” because “apple” exists in the $fruits array.
Next, let’s look at some different situations.
Case 1: For simple value types, the in_array() function uses relaxed mode by default, that is, the type will not be considered. For example:
$numbers = array(1, 2, 3, 4, 5); if (in_array("2", $numbers)) { // 注意,这里的 2 是一个字符串 echo "2 存在于数组中"; }
The output result of this code will also be "2 exists in the array", even if "2" is a string, it can be matched successfully.
To use strict mode, you need to set the third parameter to TRUE. For example:
$numbers = array(1, 2, 3, 4, 5); if (in_array("2", $numbers, TRUE)) { echo "2 存在于数组中"; } else { echo "2 不是数组的元素"; }
The output of this code will be "2 is not an element of the array" because in strict mode, "2" and 2 are different types and cannot be matched successfully.
Case 2: For values of composite types (for example, arrays), the in_array() function also uses relaxed mode by default, that is, as long as one of the elements matches successfully, the entire value will be considered a successful match. . For example:
$person1 = array("name" => "John", "age" => 30); $person2 = array("name" => "Mary", "age" => 25); $people = array($person1, $person2); if (in_array(array("name" => "John"), $people)) { echo "有一个人叫 John!"; }
The output of this code will be "There is a person named John!" because the "name" element of $person1 is matched successfully.
Case 3: When the value in the target array is NULL, the in_array() function does not consider that the value does not exist. For example:
$values = array("a", "b", NULL); if (in_array(NULL, $values)) { echo "NULL 存在于数组中"; }
The output of this code will be "NULL exists in array".
In summary, the in_array() function is a very practical function and is widely used. When you need to determine whether a value exists in an array during development, you can give priority to using this function. At the same time, be careful to use strict mode to avoid type mismatch problems.
The above is the detailed content of PHP common function analysis: in_array(). For more information, please follow other related articles on the PHP Chinese website!