Phpin_array functions-PHP source code

Source: Internet
Author: User
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

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.