4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで「含む」かどうかを書く場合(文字列、配列)

Last updated at Posted at 2017-09-11

いざ書こうと思ってついグーグル先生に聞いてしまうので、メモ。

文字列

strpos

if(strpos($str,'hoge') !== false){
  //'hoge'が含まれている場合
}

if(strpos($str,'fuga') === false){
  //'fuga'が含まれていない場合
}

出現する位置を返すため、型比較する必要がある(===,!==)

(参考)
http://qiita.com/kazu56/items/2c72d187438de07c2503
http://php.net/manual/ja/function.strpos.php

配列

in_array

if(in_array('hoge',$arr,true)){
  //'hoge'が含まれている場合
}

if (in_array(array('hoge', 'fuga'), $arr,true)) {
  //配列'hoge','fuga'がある場合
}

(参考)
http://www.t-net.ne.jp/~cyfis/php/judge/in_array.html
http://php.net/manual/ja/function.in-array.php

【追記】
in_array()は第3引数を指定しないと型比較を行わないので、
その場合、思わぬところでハマる可能性があります。。。
(コメント参照)

4
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?