On the use of PHP In_array functions

Source: Internet
Author: User


First, introduce the requirements background:

Invoice method:
0= donation (Don't ask me why, historical reasons)
1= sent to China
2= Request
3= Electronic Invoice

Now you want to test the data submitted by the User:

if (!in_array ($_post[' invoice_action '), Array (0,1,2,3))) {
throw new Exception (' Please select the correct invoice method ');
}

This time there is a problem, if there is no $_post[' invoice_action ' value, why not throw an exception?
This is confirmed as a pit of PHP as a weakly typed language!!! Yes, it's a pit!!!.
Take a look at this set of code:


Echo In_array (', array (0))?     1:0; Results: 1
echo In_array (null, array (0))?   1:0; Results: 1
Echo In_array (False, array (0))?  1:0; Results: 1

How are we going to get around or fill out this big hole?
Method One: In_array supports the third parameter, forcing data type detection


Echo In_array (", array (0), true)?"     1:0; Results: 0
echo In_array (null, array (0), true)?   1:0; Results: 0
Echo In_array (False, array (0), true)?  1:0; Results: 0

Method Two: Still is the data type direction, changes the array 0 to the string


Echo In_array (', Array (' 0 '), true)? 1:0;    //Result: 0
Echo in_array (null, Array (' 0 '), t Rue)? 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.