-3

This is my code,

  $em= strpos($str, 'something');
  $em2= strpos($str, 'something2');
  $em3= strpos($str, 'something3');
////////triggering only if either of them exist

  if (($em!== false)||($em2!== false)||($em3!== false)) {
  some action
  }

Is my coding correct? or I am missing anything? Please suggest.

Should it be like ?

 if (!(($em== false)||($em2== false)||($em3 == false))) {
Timothy Groote
  • 8,614
  • 26
  • 52
Abul Hasnat
  • 1,541
  • 2
  • 16
  • 23

5 Answers5

2

To check if strpos() did not find any occurence of the substring you need to use === (which compares the value and the type) because strpos() may also return 0 which evaluates to false when compared with ==.

Edit: The author edited his question. This answer covers the original question.

nkr
  • 3,026
  • 7
  • 31
  • 39
1

If you are checking for a boolean, you should always use === or !==.

The main reason for that is in PHP, $Test == 1 or $Test == TRUE or ($Test) is the same if the value of $Test is not empty.

About your parantheses. If you have more then 1 logic to apply, use them, if not, optional.

if($Test === TRUE OR $Foo === TRUE){

}

and

if($Test === TRUE OR ($Foo === TRUE AND $Bar === TRUE)){

}

Also, instead of using || or && to check for TRUE or FALSE, use OR or AND against a boolean.

David Bélanger
  • 7,400
  • 4
  • 37
  • 55
  • 1
    since Abul uses `$em= strpos($str, 'something');` you might also want to explain to him why he should then cast $em to make sure it's a boolean... – Timothy Groote Aug 13 '12 at 13:58
  • Because later I will use those $em positions for my functions. – Abul Hasnat Aug 14 '12 at 01:01
  • @AbulHasnat Timothy is a bit right. This function return not only `FALSE` but also the real position in the string (`INTEGER`). If you cast the function as a `BOOL`, it will either be `FALSE` or `TRUE`. In this case, `TRUE` will be `$em >= 1`. – David Bélanger Aug 14 '12 at 14:25
0

some of your parentheses (( )) aren't necesary but it should work like this.

if (!($em=== false || $em2=== false || $em3 === false)) {
       // do something
}
Timothy Groote
  • 8,614
  • 26
  • 52
0

Both the cases give the same result. What is your intention is not correctly mentioned. Are you getting any error here?

You can find more at http://www.phpsyntax.blogspot.in

0

if you search something,something2,something3 in a text which is in $str it's ok.

but if you thought to find a string from $str in something,something2 or something3 it's here the issue.

you should have a look at this php.net/manual/en/function.strpos.php

regards