ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

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
تم إضافة السؤال من قبل Anirban Chakraborty , Network Administrator , Wipro Limited
تاريخ النشر: 2017/01/17
Reham Alfaqeer
من قبل 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
من قبل 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 . "\\\\\\\\"";

}

 

مستخدم محذوف‎
من قبل مستخدم محذوف‎

Thank you,

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

Daniyal Ahmad
من قبل 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
من قبل 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 . "\\\\\\\\"";

}

المزيد من الأسئلة المماثلة