0

Is there a way to combine

 if ((strpos($str,"abc") !== false) and (strpos($str,"abc") < 1000))

Or do I need two ifs for that? Because if abc isn't in the string the position is -1 so smaller than 1000.

I am only interested if php have some special for this problem ;)

Is this:

if (strpos(substr($str,0,1000),"abc") !== false) 

a good way for it?

Wikunia
  • 1,564
  • 1
  • 16
  • 37

3 Answers3

2
$pos_abc = strpos($str, 'abc');
if ($pos_abc !== false && $pos_abc < 1000)

You want to test two different things: 1- is abc in the string ? and 2- is abc in the first thousand characters of that string. While it is possible to rewrite it in a single test, it provides no benefit, and it would actually costs a lot of clarity in your code.

Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
0

You could try this if you want:

if( in_array(strpos($str,"abc"),range(0,1000),true))

However it doesn't look any simpler and it comes at a quite severe performance cost.

Perhaps the best way would be to use a variable:

$pos = strpos($str,"abc");
if( $pos !== false && $pos < 1000) ...
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

two issues:

  • your double strpos
  • the comparison (2. and operator) depends on the first, which may cause issues (eg. in later php versions)

UPDATE:

the nice and quick solution pattern:

if(($pos = strpos($str,"abc") !== false)?($pos < 1000):false)

the nice and clean solution pattern:

$pos = strpos($str,"abc");
if(($pos !== false)?($pos < 1000):false)
Quicker
  • 1,247
  • 8
  • 16
  • assignation inside an if like that is really not good a good habit to take for clarity. "Did you mean to assign, or is it a typo while you meant a comparison ?". I understand you answered the question, but this should be avoided. This solution is anything but "nice and clean" – Lepidosteus Oct 02 '13 at 09:08