PHP in_array implicit conversion solution, phpin_array

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.