The in_array function is used to determine whether the specified content exists in the data. It is very simple to use this function, but I will find some problems during use, let's take a look at how to solve these problems. The in_array function is used to determine whether the specified content exists in the data. It is very simple to use this function, but I will find some problems during use, let's take a look at how to solve these problems.
Script ec (2); script
First, we will introduce the background:
Invoice method:
0 = donation (do not ask me why, historical reasons)
1 = forward
2 = request
3 = electronic invoice
Check the data submitted by the user:
If (! In_array ($ _ POST ['invoice _ action'], array (0, 1, 2, 3 ))){
Throw new Exception ('select the correct invoice method ');
}
At this time, a problem occurs. If the value $ _ POST ['invoice _ action'] does not exist at all, why didn't an exception be thrown?
It has been confirmed that this is a pitfall of PHP as a weak language !!! That's right. This is a pitfall !!!
Let's take a look at this set of code:
Echo in_array ('', array (0 ))? 1: 0; // result: 1
Echo in_array (null, array (0 ))? 1: 0; // result: 1
Echo in_array (false, array (0 ))? 1: 0; // result: 1
How can we bypass or fill in such a big pitfall?
Method 1: in_array supports the third parameter, which forces data type detection.
Echo in_array ('', array (0), true )? 1: 0; // result: 0
Echo in_array (null, array (0), true )? 1: 0; // result: 0
Echo in_array (false, array (0), true )? 1: 0; // result: 0
Method 2: change the value 0 in the array to a string.
Echo in_array ('', array ('0'), true )? 1: 0; // result: 0
Echo in_array (null, array ('0'), true )? 1: 0; // result: 0
Echo in_array (false, array ('0'), true )? 1: 0; // result: 0