PHP in_array implicit conversion solution, phpin_array
Problem
When writing an interface today, You need to input a large number of basic information parameters, which are int and string types. For convenience of verification, I plan to put all the parameters in the array, and then use in_array (0, $ param) to judge whether the int parameter is 0, and then separately determine whether the string parameter is null. The sample code is as follows:
If (in_array (0, $ param) | $ param ['img '] = '') {$ this-> errorCode = 10030; $ this-> errorMessage = 'incorrect parameter '; return false ;}
However, during self-testing, if you pass in the correct parameters, an incorrect parameter prompt will be returned !!!
Cause
This is precisely because of in_array. in_array (search, array) is equivalent to comparing each value in the array with search. Because I $ param array contains the int parameter, there is also a string parameter, which is equivalent to comparing with string and int. The implicit conversion rules of PHP are as follows:
Non-numeric string and integer comparison, the string is automatically converted to int (0)
The following example demonstrates our statement:
<?php $a = (int)'abc'; var_dump($a); //int(0) $c = array(0,1,2,3); if(in_array('abc', $c)) { echo 'exist'; } else { echo 'not exist'; } //exist
Solution
The third parameter "true" is added to in_array to check whether the searched data is of the same type as the array value, in this way, the function returns true only when the element exists in the array and the data type is the same as the given value.
For the services I have shown above, we can be more rigorous. We can store int-type data in an array, string in an array, and two arrays of different types for data verification, this will not cause the above problems.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.