Problems and solutions of using In_array functions in PHP _php tips

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:

Php;auto-links:false; " >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'] such value, why not throw an exception?

It is confirmed that this is PHP as a weak type language of a pit, yes, it is 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;//Result: 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;   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 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 '), true)? 1:0;  Result: 0
Echo In_array (False, Array (' 0 '), true)? 1:0;//Result: 0

Summarize

The above is about PHP in the use of In_array functions encountered problems and solutions, I hope this article on the same problem with friends can help, if you have questions can be exchanged message.

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.