imns
imns

Reputation: 5082

php version of pythons if in

Python has the great: if sub-string in string, like this:

if "fox" in "The quick brown fox jumps over the lazy dog":
   print True

Does does PHP have something equivalent to this?

Upvotes: 3

Views: 65

Answers (4)

wajiw
wajiw

Reputation: 12269

There's a few ways. One is:

if(stristr('fox','The quick brown fox jumps over the lazy dog') !== FALSE){
...code
}

http://php.net/manual/en/function.stristr.php

stripos and others may be more efficient. See PHP String Functions

Upvotes: 1

JAL
JAL

Reputation: 21563

Yes, see stripos and strpos

if(stripos("The quick brown fox jumps over the lazy dog","fox")!==false)
   { echo 'True'; }

stripos and strpos return the position at which the match started, so you need to use strict comparison (=== or !==) to avoid a false negative when the needle is at pos. 0 in the haystack.

You may prefer stristr, which just returns the matched string or boolean false.

in_array works about the same as in does in Python for lists and dictionaries, if you are also thinking beyond strings.

Upvotes: 3

eykanal
eykanal

Reputation: 27017

There's three that I can think of: substr, strpos, and strstr. Each of those are case sensitive, and there are also case insensitive versions of those functions as well. PHP has a ridiculous number of string handling commands, so really just peruse the string section of the manual until you see the one you want.

Upvotes: 1

simshaun
simshaun

Reputation: 21466

strpos

Upvotes: 2

Related Questions