- array_key_exists
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- in_array
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 8 notes
- in_array
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- PHP in_array() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
array_key_exists
array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index.
Parameters
An array with keys to check.
Return Values
Returns true on success or false on failure.
Note:
array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.
Examples
Example #1 array_key_exists() example
$search_array = array( ‘first’ => 1 , ‘second’ => 4 );
if ( array_key_exists ( ‘first’ , $search_array )) echo «The ‘first’ element is in the array» ;
>
?>?php
Example #2 array_key_exists() vs isset()
isset() does not return true for array keys that correspond to a null value, while array_key_exists() does.
$search_array = array( ‘first’ => null , ‘second’ => 4 );
?php
// returns false
isset( $search_array [ ‘first’ ]);
// returns true
array_key_exists ( ‘first’ , $search_array );
?>
Notes
Note:
For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array . This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0.
To check whether a property exists in an object, property_exists() should be used.
See Also
- isset() — Determine if a variable is declared and is different than null
- array_keys() — Return all the keys or a subset of the keys of an array
- in_array() — Checks if a value exists in an array
- property_exists() — Checks if the object or class has a property
User Contributed Notes 3 notes
When you want to check multiple array keys:
$array = [];
$array [ ‘a’ ] = » ;
$array [ ‘b’ ] = » ;
$array [ ‘c’ ] = » ;
$array [ ‘d’ ] = » ;
$array [ ‘e’ ] = » ;
// all given keys a,b,c exists in the supplied array
var_dump ( array_keys_exists ([ ‘a’ , ‘b’ , ‘c’ ], $array )); // bool(true)
function array_keys_exists (array $keys , array $array ): bool
$diff = array_diff_key ( array_flip ( $keys ), $array );
return count ( $diff ) === 0 ;
>
In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??
So for a three dimensional array where you are not sure about any of the keys actually existing
// use:
$exists = array_key_exists ( $key3 , $arr [ $key1 ][ $key2 ]??[]) ;
I took hours for me to debug, and I finally recognized that,
You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
in_array
Searches for needle in haystack using loose comparison unless strict is set.
Parameters
Note:
If needle is a string, the comparison is done in a case-sensitive manner.
If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .
Note:
Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.
Return Values
Returns true if needle is found in the array, false otherwise.
Examples
Example #1 in_array() example
$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Got mac» ;
>
?>?phpThe second condition fails because in_array() is case-sensitive, so the program above will display:
Example #2 in_array() with strict example
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» ;
>
?>The above example will output:
1.13 found with strict check
Example #3 in_array() with an array as needle
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» ;
>
?>The above example will output:
See Also
- array_search() — Searches the array for a given value and returns the first corresponding key if successful
- isset() — Determine if a variable is declared and is different than null
- array_key_exists() — Checks if the given key or index exists in the array
User Contributed Notes 8 notes
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.
$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 ); // truein_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 ); // falseI got an unexpected behavior working with in_array. I’m using following code:
// .
$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.
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*:
$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.
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.Here is a recursive in_array function:
$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 ;
>
>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.
$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!’ );in_array
Ищет в haystack значение needle . Если strict не установлен, то при поиске будет использовано нестрогое сравнение.
Список параметров
Замечание:
Если needle — строка, сравнение будет произведено с учетом регистра.
Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack .
Возвращаемые значения
Возвращает TRUE , если needle был найден в массиве, и FALSE в обратном случае.
Примеры
Пример #1 Пример использования in_array()
$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Нашел Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Нашел mac» ;
>
?>?phpВторого совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:
Пример #2 Пример использования in_array() с параметром strict
if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ найдено со строгой проверкой\n» ;
>if ( in_array ( 1.13 , $a , true )) echo «1.13 найдено со строгой проверкой\n» ;
>
?>Результат выполнения данного примера:
1.13 найдено со строгой проверкой
Пример #3 Пример использования in_array() с массивом в качестве параметра needle
if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ найдено\n» ;
>if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ найдено\n» ;
>if ( in_array ( ‘o’ , $a )) echo «‘o’ найдено\n» ;
>
?>Результат выполнения данного примера:
Смотрите также
- array_search() — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
- isset() — Определяет, была ли установлена переменная значением отличным от NULL
- array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
PHP in_array() Function
Search for the value «Glenn» in an array and output some text:
$people = array(«Peter», «Joe», «Glenn», «Cleveland»);
?php
if (in_array(«Glenn», $people))
echo «Match found»;
>
else
echo «Match not found»;
>
?>Definition and Usage
The in_array() function searches an array for a specific value.
Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
Syntax
Parameter Values
Parameter Description search Required. Specifies the what to search for array Required. Specifies the array to search type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array. Technical Details
Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise PHP Version: 4+ PHP Changelog: PHP 4.2: The search parameter may now be an array More Examples
Example
$people = array(«Peter», «Joe», «Glenn», «Cleveland», 23);
?php
if (in_array(«23», $people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
if (in_array(«Glenn»,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>if (in_array(23,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
?>COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.