Use the = Operator in PHP to compare strings

Source: Internet
Author: User
Tags comparison table

A new article recently published on Greg Beaver's blog about comparing strings in PHP with the = operator mentions the = operator of PHP when comparing strings..

In some cases, PHP converts a numeric data (such as a string containing digits) to a numeric value. The = Operator is one of them. When the = Operator is used to loosely compare two strings, PHP converts the string of the class value to a numerical value for comparison. The following experiment confirms this conclusion:

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

The output result of the above Code is:
Bool (true)

Therefore, when comparing strings, we recommend that you use the = Operator to strictly check strings or use functions such as strcmp () to avoid possible problems. The PHP type comparison table in the PHP Manual also describes this in detail.

In addition, common in_array () functions also have weak types. See the following code:

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

The output result of the above Code is:
Bool (true)

I believe that PHP programmers who have used this function for security checks all know what security issues will occur? Fortunately, the in_array () function provides us with the third parameter. Setting it to true enables the forced type check mechanism of the in_array () function, as shown in the following code:

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

Output result:
Bool (false)

Since PHP is a weak language, the concept of data type is weakened in PHP. Therefore, if the data type is excessively neglected during programming (which is also a common problem for most PHP programmers), some problems may occur and even cause security vulnerabilities. Finally, if that sentence is annoying, it will strictly check and filter external data.

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.