Home > Backend Development > PHP Tutorial > Problems and solutions when using in_array function in PHP

Problems and solutions when using in_array function in PHP

高洛峰
Release: 2023-03-03 21:58:02
Original
1151 people have browsed it

First introduce the demand background:

Invoice method:

0=Donation (don’t ask me why, historical reasons)

1=Send in the center

2=Request

3=Electronic invoice

Now we need to match The data submitted by the user is tested:

php;auto-links:false;">if(!in_array($_POST['invoice_action'], array(0,1,2,3))){
  throw new Exception('请选择正确的发票方式');
}
Copy after login

A problem arises at this time. If the value $_POST['invoice_action'] does not exist at all, why is no exception thrown?

After confirmation, this is what PHP does A pitfall of weakly typed languages, yes, this is a pit.

Look at this set of code:

echo in_array('', array(0)) ? 1 : 0;   // 结果:1
echo in_array(null, array(0)) ? 1 : 0;  // 结果:1
echo in_array(false, array(0)) ? 1 : 0; // 结果:1
Copy after login

Such a big pit, how do we bypass or fill it?

Method 1: in_array supports the third parameter, forcing data type detection

echo in_array('', array(0), true) ? 1 : 0;   // 结果:0
echo in_array(null, array(0), true) ? 1 : 0;  // 结果:0
echo in_array(false, array(0), true) ? 1 : 0; // 结果:0
Copy after login

Method 2: Still in the data type direction, change the 0 in the array to a string

echo in_array('', array('0'), true) ? 1 : 0;   // 结果:0
echo in_array(null, array('0'), true) ? 1 : 0;  // 结果:0
echo in_array(false, array('0'), true) ? 1 : 0; // 结果:0
Copy after login

Summary

The above is about Problems and solutions encountered when using the in_array function in PHP. I hope this article can be helpful to friends who also encounter this problem. If you have any questions, you can leave a message to communicate.


For more related articles on problems and solutions when using the in_array function in PHP, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template