The Solution of Implicit Conversion of in_array in PHP

  • 2021-09-12 00:33:47
  • OfStack

Problem

Today, when writing an interface, I need to pass in a large number of basic information parameters, which are int and string. For the convenience of verification, I intend to put all the parameters in an array, and then use in_array (0, $param) to judge whether the int parameter is 0, and then judge whether the string parameter is empty separately. The example code is as follows:


      if(in_array(0, $param) || $param['img'] == '') {
        $this->errorCode = 10030;
        $this->errorMessage = ' Incorrect parameter ';
        return false; 
      }

However, when self-testing, it is found that if the correct parameters are passed in, the prompt that the parameters are incorrect will be returned! ! !

Cause

This happens precisely because of the trouble caused by in_array. in_array (search, array) is equivalent to comparing each value in the array with search. Because my $param array has an string parameter in addition to int parameter, which is equivalent to comparing string with int, the implicit conversion rule of PHP is as follows:

Non-numeric string and integer comparison, string 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 data being searched is of the same type as the value of the array, so that the function returns true only if the element exists in the array and the data type is the same as the given value

Aiming at the business that I appear above, I can be more rigorous. One array is stored for int type data, and one array is stored for string type data. Two different types of arrays are checked for data respectively, so that the above problems will not occur


Related articles: