PHP Best Practices----detect whether a value is null or FALSE

Source: Internet
Author: User
Use the = = = operator to detect null and Boolean false values.

PHP's loose type system provides many different ways to detect a variable's value. However, this has caused a lot of problems. Use = = to detect whether a value is null or FALSE, and false if the value is actually an empty string or 0. Isset is not appropriate to detect whether a variable has a value, rather than detecting whether the value is null or FALSE.

The Is_null () function can accurately detect whether a value is Null,is_bool can detect whether a value is a Boolean value (such as false), but there is a better choice: = = operator. = = = Detect whether two values are the same, which is different from the equivalent in the PHP loose type world. It's also faster than Is_null () and Is_bool (), and some people think it's a bit cleaner than using a function.

Example

<?php
$x = 0;
$y = null;

is $x null?
if ($x = = null)
    print (' oops! $x is 0, not null! ');

is $y null?
if (Is_null ($y))
    print (' great, but could be faster. ');

if ($y = = null)
    print (' perfect! ');

Does the string ABC contain the character a?
if (Strpos (' abc ', ' A '))
    //gotcha!  Strpos returns 0, indicating it wishes to return the position of the the ' the ' the ' the ' the '.
    But PHP Interpretes 0 as false, so we never to this print statement!
    Print (' Found it! ');

Solution:use!== (the opposite of = =) to the If Strpos () returns 0, or Boolean false.   
if (Strpos (' abc ', ' A ')!== false)
    print (' Found it for Real this time! ');
? >

Traps test a return value for a function that returns 0 or Boolean false, such as Strpos (), always use = = = and!==, otherwise you will encounter problems.

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.