1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

What Is the Best Way to Test the strpos() Return Value in PHP?

Discussion in 'PHP' started by beingchinmay, Aug 6, 2015.

  1. beingchinmay

    beingchinmay Banned

    Joined:
    Aug 5, 2015
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate "0" and "false". Check out this PHP script on how to use strpos()


    Code:
    <?php
    $haystack = "needle234953413434516504381640386488129";
    $pos = strpos($haystack, "needle");
    if ($pos==false) {
      print("Not found based (==) test
    ");
    } else {
      print("Found based (==) test
    ");
    }
    if ($pos===false) {
      print("Not found based (===) test
    ");
    } else {
      print("Found based (===) test
    ");
    }
    ?>
    This script will print:
    Not found based (==) test
    Found based (===) test
    Of course, (===) test is correct
     
  2. alia123

    alia123 New Member

    Joined:
    Jan 8, 2016
    Messages:
    65
    Likes Received:
    4
    Trophy Points:
    0

Share This Page