Question

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?

Was it helpful?

Solution

$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.

OTHER TIPS

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) ...

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top