Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Consider the following code:

$str1 = 'yabadabadoo';

$str2 = 'yaba';

if (strpos($str1,$str2))

        { echo "\\\\"" . $str1 . "\\\\" contains \\\\"" . $str2 . "\\\\"";

  }else {

            echo "\\\\"" . $str1 . "\\\\" does not contain \\\\"" . $str2 . "\\\\"";

}

The output will be: "yabadabadoo" does not contain "yaba"

Why? How can this code be fixed to work correctly?

user-image
Question added by Anirban Chakraborty , Network Administrator , Wipro Limited
Date Posted: 2017/01/17
Reham Alfaqeer
by Reham Alfaqeer , PHP Web Developer , Syarah.com

strpos will return the first occurrence of the 2nd parameter in the first parameter string , so the output of strpos($str1,$str2) will be 0= false and the output always will be that in the else statement , you can change the if condition to==>  if (strpos($str1,$str2)>-1) since the strpos function will return -1 if the string does not contain the 2nd str.   

Jonathan de Flaugergues
by Jonathan de Flaugergues , software engineer , Abbeal

The strpos return a number which represent the position of where the $str1 is in $str2.

In this case, the return value if '0' because yabadabadoo start by yaba.

So, the condition strpos($str1,$str2) is false because the number is considered as false when it's converted to boolean.

 

To fixed it, you have to compare the condtion with a boolean.

 

$str1 = 'yabadabadoo';

$str2 = 'yaba';

if (strpos($str1,$str2) !== false)

  { echo "\\\\\\\\"" . $str1 . "\\\\\\\\" contains \\\\\\\\"" . $str2 . "\\\\\\\\"";

} else {

  echo "\\\\\\\\"" . $str1 . "\\\\\\\\" does not contain \\\\\\\\"" . $str2 . "\\\\\\\\"";

}

 

Deleted user
by Deleted user

Thank you,

I agree with the answer of Jonathan. You can also use "===" instead "!==" and inverse echo for if - else statement.

Daniyal Ahmad
by Daniyal Ahmad , Software Applications Developer / implementation manager , Megaplus Pakistan

if( strpos($str1,$str2) > -1 ){

        { echo "\\\\\\\\\\\\\\\\"" . $str1 . "\\\\\\\\\\\\\\\\" contains \\\\\\\\\\\\\\\\"" . $str2 . "\\\\\\\\\\\\\\\\"";

  }else {

            echo "\\\\\\\\\\\\\\\\"" . $str1 . "\\\\\\\\\\\\\\\\" does not contain \\\\\\\\\\\\\\\\"" . $str2 . "\\\\\\\\\\\\\\\\"";

}

Adel Ezat Fawzy Ellozy
by Adel Ezat Fawzy Ellozy , Webdeveloper. , Saudi Arabian Maritiem Sports Federation

Note that string positions start at 0 .

 'yaba' come at the beginning of the string so strpos return 0 , and  if statement evaluates 0 as false .

 

so you can use :

 

if( strpos($str1,$str2) > -1 ){

        { echo "\\\\\\\\"" . $str1 . "\\\\\\\\" contains \\\\\\\\"" . $str2 . "\\\\\\\\"";

  }else {

            echo "\\\\\\\\"" . $str1 . "\\\\\\\\" does not contain \\\\\\\\"" . $str2 . "\\\\\\\\"";

}

More Questions Like This