Home > Article > Backend Development > Problems and solutions when using in_array function in PHP
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('请选择正确的发票方式'); }
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
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
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
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!