Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    9
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Why is this conditional statement not evaluating like I expect it too?

    Hey guys,

    I'm a bit stumped on this one. I would have expected the following code to echo "string contains either 123 or abc". But it doesn't! Any idea why?

    PHP Code:
    <?php

    $string 
    "123 abc";

    $needle strpos($string"123");
    $needle2 strpos($string"def");

        if ((
    $needle === true) || ($needle2 === true)) {
            echo 
    "string contains either 123 or abc";
        } else {
            echo 
    "string does NOT contain either 123 or abc";
        }

    ?>
    Am I doing something wrong? Or is there a better way to check whether a string contains either of two specific substrings?
    Last edited by BMAN99; 07-29-2012 at 02:04 PM.

  • #2
    Senior Coder
    Join Date
    Aug 2006
    Posts
    1,138
    Thanks
    7
    Thanked 257 Times in 256 Posts
    If it finds the string, strpos returns the position of the string, not "true". So you could test != false, but I don't think it will ever return "true".
    Code:
        if (strpos($string, "123") || strpos($string, "def")) {
    ...
    Dave

  • Users who have thanked tracknut for this post:

    BMAN99 (07-29-2012)

  • #3
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    tracknut is mostly correct. strpos() won't ever return an explicit TRUE. It will be FALSE or a number. So, your conditions should look more like this:
    PHP Code:
    $needle strpos($string"123"); 
    $needle2 strpos($string"def"); 

        if (
    $needle !== false || $needle2 !== false) { 
            echo 
    "string contains either 123 or abc"
        } else { 
            echo 
    "string does NOT contain either 123 or abc"
        } 
    You want to test for explicit, "!==", not false because with PHP's loose type conversion if the substring position is 0(at the beginning of the string) it will evaluate to false with "!=" and your result will be incorrect.

  • Users who have thanked Inigoesdr for this post:

    BMAN99 (07-29-2012)

  • #4
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    9
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Thanks guys! That makes sense.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •