Using the = = operator in PHP for string comparison _php tips

Source: Internet
Author: User
Tags comparison table
A new article recently published on Greg Beaver's blog comparing Strings in php and the = = operator mentions the problems that PHP's = = operator should pay attention to when comparing strings.

in some cases, PHP converts class numeric data (such as strings containing numbers) to numeric processing, and the = = operator is one of them. When you use the = = operator to loosely compare two strings, PHP The string conversion of a class value is compared to a numeric value, and the following experiment confirms this conclusion:

<?php
var_dump('01' == 1);
?>

the above code output results are:
BOOL (TRUE)

Therefore, it is recommended that you use the = = operator to strictly examine the string, or use functions such as strcmp (), to avoid problems that may arise when comparing strings. This is also explained in detail in the PHP manual, the PHP type comparison table.

In addition, the common In_array () function also has a weak type of problem, see the following code:

<?php
var_dump(in_array('01', array('1')));
?>

the above code output results are:
BOOL (TRUE)

do you believe that a PHP programmer who uses this function for security checks knows what kind of security problem this will have? Fortunately The In_array () function provides us with a third argument, and sets it to true to open the the mandatory type checking mechanism for the In_array () function, as shown in the following code:

<?php
var_dump(in_array('01', array('1'), true));
?>

the output results are:
BOOL (FALSE)

because PHP is a weak type of language, the concept of data type isWeakening. Therefore, if the data type is ignored in programming (which is also a common problem for most PHP programmers), it can cause some problems and even lead to security vulnerabilities. Finally, the sentence is very annoying and annoying, the external data is strictly checked and filtered.

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.