Home >Backend Development >PHP Tutorial >Introduction to the usage of in_array function in php
This article brings you an introduction to the usage of the in_array function in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Do you think the following code will output true or false?
1 <?php 2 $data = [6,9]; 3 var_dump(in_array('06',$data));
Today when debugging the code, I found a bug caused by the incorrect use of in_array. In PHP, array is a very powerful data structure. The official provides a lot of array operation functions. in_array() is a commonly used one. We often use it to determine whether an array contains an element. But we may ignore the third parameter of the function when using it, resulting in a type of bug.
Official function definition:
in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
: bool
needle
required Elements to be found
Haystack
Array to be searched
Strict
If this parameter is set to true, strict comparison mode will be used to find elements. That is to say, when searching, not only the values of the element to be searched and the array elements are compared, but also their types are compared. Default is false.
If the third parameter is ignored, the output of the question at the beginning of the article will be true. Because strict comparison is not used, the function will try to convert the string to an integer/floating point type for comparison when processing strings and numbers. For example, '12ax' will be converted to 12. Then, the above '06' will be converted to 6, so the output is true.
At first, I didn’t notice that the function had a third parameter setting, so I couldn’t get the result I wanted no matter what.
The above is the detailed content of Introduction to the usage of in_array function in php. For more information, please follow other related articles on the PHP Chinese website!