0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPでin_arrayを使ってない?大量データならissetの方が速い理由

0
Last updated at Posted at 2026-04-07

はじめに

PHPで配列に値が含まれているかチェックするとき、
つい in_array を使っていませんか?

in_array($needle, $array);

自分も普通にこれを使っていましたが、
あるときパフォーマンスを調べていて気づきました。

👉 データ量が増えると結構遅い

そして代替としてよく出てくるのが isset です。

isset($map[$key]);

この記事では、

  • なぜ isset の方が速いのか
  • どのくらい差が出るのか
  • 実務でどう使い分けるべきか

をまとめます。


結論

先に結論です:

  • in_array → O(n)(線形探索)
  • isset → O(1)(ハッシュアクセス)

👉 大量データなら isset の方が圧倒的に速い


なぜ遅いのか(in_array)

in_array($needle, $array);

内部的には:

👉 配列の先頭から順番に探していく

つまり:

  • 見つかるまで全部見る可能性がある
  • 最悪ケースは全探索

なぜ速いのか(isset)

isset($map[$key]);

これは:

👉 キーの存在チェック

PHPの配列はハッシュテーブルなので、

  • キーから直接アクセスできる
  • 探索がほぼ一定時間

比較イメージ

方法 やっていること 計算量
in_array 値を1個ずつ比較 O(n)
isset キーに直接アクセス O(1)

実務での書き換え例

before(よくある)

$allowed = ['apple', 'banana', 'orange'];

if (in_array($target, $allowed)) {
    // OK
}

after(高速化)

$allowed = [
    'apple' => true,
    'banana' => true,
    'orange' => true,
];

if (isset($allowed[$target])) {
    // OK
}

ベンチマーク(簡易)

$size = 100000;

$array = range(1, $size);
$map = array_flip($array);

$target = $size;

$start = microtime(true);
in_array($target, $array);
echo "in_array: " . (microtime(true) - $start) . PHP_EOL;

$start = microtime(true);
isset($map[$target]);
echo "isset: " . (microtime(true) - $start) . PHP_EOL;

👉 結果(例)

in_array: 0.01秒
isset: 0.000001秒

👉 桁が違う


注意点(ここ重要)

① 値ではなく「キー」を見る必要がある

isset は値検索ではなくキー検索なので、

👉 データ構造を変える必要がある


② nullは検出できない

$map = ['a' => null];

isset($map['a']); // false

👉 nullを扱う場合は注意


③ 可読性とのトレードオフ

  • in_array → 直感的
  • isset → 最適化寄り

👉 小規模データなら無理に変えなくてもいい


使い分け

in_arrayを使うべき場面

  • データ量が少ない
  • 可読性重視
  • 一時的なチェック

issetを使うべき場面

  • 大量データ
  • 頻繁にチェックする処理
  • パフォーマンスが重要

まとめ

  • in_array は便利だが O(n)
  • isset は高速(O(1))
  • 大量データでは差が大きい

👉 パフォーマンス気にするならデータ構造から考える


おわりに

今回のポイントはこれです:

「関数を変える」ではなく「データ構造を変える」

この視点を持つと、パフォーマンス改善の幅が一気に広がります。

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?