Home >Backend Development >PHP Tutorial >Detailed explanation of implicit conversion examples of in_array in PHP
When writing an interface today, I need to pass in a large number of basic information parameters. The parameters are of two types: int and string. For the convenience of verification, I plan to put all the parameters in an array, and then use in_array (0, $param) determines whether the int parameter is 0, and then separately determines whether the string parameter is empty. The sample code is as follows:
if(in_array(0, $param) || $param['img'] == '') { $this->errorCode = 10030; $this->errorMessage = '参数不正确'; return false; }
However, it was found during the self-test , if you pass in the correct parameters, a prompt indicating that the parameters are incorrect will be returned! ! !
Reason
This situation occurs precisely because in_array is causing trouble. in_array(search,array) is equivalent to combining each value in the array with search Comparison, since in addition to the int parameter in my $param array, there is also a string parameter, which is equivalent to using string and int to compare. PHP's implicit conversion rules:
Non-numeric strings and integers Comparison, the string is automatically converted to int(0)
The following example verifies 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
in_array adds a third parameter true to check whether the type of the searched data and the value of the array are the same. In this way, the function can only be used when the element exists in the array and the data type is the same as the given one. True will be returned only when the fixed values are the same
For the business I presented above, you can be more rigorous. Store int data in an array, string in an array, and perform data verification on the two different types of arrays. In this way, the above problems will not occur
Related recommendations:
About some examples of implicit conversion and summary in JavaScript
How to use implicit conversion? Summarize the usage of implicit conversion examples
javascript implicit conversion details
The above is the detailed content of Detailed explanation of implicit conversion examples of in_array in PHP. For more information, please follow other related articles on the PHP Chinese website!