PHP 8.3.4 Released!

in_array

(PHP 4, PHP 5, PHP 7, PHP 8)

in_array配列に値があるかチェックする

説明

in_array(mixed $needle, array $haystack, bool $strict = false): bool

haystack 内の needle を検索します。 strict が設定されていない限りは型の比較は行いません。

パラメータ

needle

探す値。

注意:

needle が文字列の場合、 比較の際に大文字小文字は区別されます。

haystack

配列。

strict

三番目のパラメータ stricttrue に設定された場合、 in_array() は、haystack の中の needleも確認します。

注意:

PHP 8.0.0 より前のバージョンでは、 strict フラグが指定されていない場合に、 配列の値が 0 の場合でも文字列にマッチしてしまっていました。逆も同じです。 これにより、望ましくない結果が生じる可能性があります。 似たようなエッジケースは他の型でも存在します。 値の型が完全にわからない場合には、 予期せぬ振る舞いを避けるために常に strict フラグを使うようにして下さい。

戻り値

配列で needle が見つかった場合に true、それ以外の場合は、false を返します。

例1 in_array() の例

<?php
$os
= array("Mac", "NT", "Irix", "Linux");
if (
in_array("Irix", $os)) {
echo
"Got Irix";
}
if (
in_array("mac", $os)) {
echo
"Got mac";
}
?>

二番目の条件式は失敗します。in_array() は大文字小文字を区別するからです。したがって次のような出力になります。

Got Irix

例2 strict を指定した in_array() の例

<?php
$a
= array('1.10', 12.4, 1.13);

if (
in_array('12.4', $a, true)) {
echo
"'12.4' found with strict check\n";
}

if (
in_array(1.13, $a, true)) {
echo
"1.13 found with strict check\n";
}
?>

上の例の出力は以下となります。

1.13 found with strict check

例3 needleが配列の場合の in_array()

<?php
$a
= array(array('p', 'h'), array('p', 'r'), 'o');

if (
in_array(array('p', 'h'), $a)) {
echo
"'ph' was found\n";
}

if (
in_array(array('f', 'i'), $a)) {
echo
"'fi' was found\n";
}

if (
in_array('o', $a)) {
echo
"'o' was found\n";
}
?>

上の例の出力は以下となります。

'ph' was found
  'o' was found

参考

  • array_search() - 指定した値を配列で検索し、見つかった場合に対応する最初のキーを返す
  • isset() - 変数が宣言されていること、そして null とは異なることを検査する
  • array_key_exists() - 指定したキーまたは添字が配列にあるかどうかを調べる

add a note

User Contributed Notes 8 notes

up
406
beingmrkenny at gmail dot com
12 years ago
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
'egg' => true,
'cheese' => false,
'hair' => 765,
'goblins' => null,
'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
up
4
Julian Sawicki
9 months ago
Here is a recursive in_array function:

<?php

$myNumbers
= [
[
1,2,3,4,5],
[
6,7,8,9,10],
];

$array = [
'numbers' => $myNumbers
];

// Let's try to find number 7 within $array
$hasNumber = in_array(7, $array, true); // bool(false)
$hasNumber = in_array_recursive(7, $array, true); // bool(true)

function in_array_recursive(mixed $needle, array $haystack, bool $strict): bool
{
foreach (
$haystack as $element) {
if (
$element === $needle) {
return
true;
}

$isFound = false;
if (
is_array($element)) {
$isFound = in_array_recursive($needle, $element, $strict);
}

if (
$isFound === true) {
return
true;
}
}

return
false;
}
up
2
Armands Rieksti
1 year ago
I'd like to point out that, if you're using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I've tested, the function works correctly:
if the array is filled with strings and you're searching for a string;
if the array is filled with Enums and you're searching for an Enum.
up
8
rhill at xenu-directory dot net
15 years ago
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle
= array(
'fruit'=>'banana', 'vegetable'=>'carrot'
);

$haystack = array(
array(
'vegetable'=>'carrot', 'fruit'=>'banana'),
array(
'fruit'=>'apple', 'vegetable'=>'celery')
);

echo
in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
up
1
leonhard dot radonic+phpnet at gmail dot com
1 year ago
I got an unexpected behavior working with in_array. I'm using following code:

<?php
// ...
$someId = getSomeId(); // it gets generated/fetched by another service, so I don't know what value it will have. P.S.: it's an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = ['dataOne', 'dataTwo'];
if (in_array($someId, $anyArray)) {
// do some work
}
// ...
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what's going on.
up
-3
thomas dot sahlin at gmail dot com
14 years ago
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow
= array('apple', 'banana', 'orange');

if (
in_array('banana', $slow))
print(
'Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset(
$fast['banana']))
print(
'Found it!');

?>
up
-7
Anonymous
1 year ago
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
up
-20
Anonymous
1 year ago
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
To Top