-2

I'm new to php. I'm trying out something with if-else in php. In the below test code, the control is always going to else. What am I missing here, please.

<?php
  $string = "I like it";
  echo "$string\n";
  echo strpos($string, 'my');
  echo "\n";
  if (strpos($string, "not") === true)
  {
      echo "Sorry, While we work on enhancing the user experience, would you like to suggest something?";
  }
  else
  {
      echo "Thank you, would you like to try again";
  }
  echo "\n";
?>
Sachin PATIL
  • 727
  • 1
  • 9
  • 15
NewLands
  • 69
  • 2
  • 10
  • It will go to else because the word 'not' is not present in your string. strpos will check if a string is present in a string. – Rotimi Mar 24 '17 at 08:18
  • 2
    See [How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?](http://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp). `strpos` returns an integer when succesful, not the boolean `true` – simon Mar 24 '17 at 08:21
  • @simon - Thank you. replacing === with == fixed the problem and the link gave me great insight on the usage. Appreciate your help on this silly question. – NewLands Mar 24 '17 at 08:53
  • Be aware that `strpos` returns 0 if the needle you're searching for is at the very beginning of the string. 0 is **not** equal to `true` and therefore your `if` statement will fail. You probably want to rewrite your statement and check for `false`, respectively `!== false` – simon Mar 24 '17 at 09:02

1 Answers1

0

strpos() is use to find the position of the first occurrence of the string Check here

<?php
echo strpos("I love php, I love php too!","php");
?>

it will return '7'

As i see your example the condition is false that's why control execute else part.