- array_key_exists
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- in_array
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- PHP in_array
- Introduction to the PHP in_array() function
- PHP in_array() function examples
- 1) Simple PHP in_array() function examples
- 2) Using PHP in_array() function with the strict comparison example
- 3) Using PHP in_array() function with the searched value is an array example
- 4) Using PHP in_array() function with an array of objects example
- Summary
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
Ищет в 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
Summary: in this tutorial, you will learn how to use the PHP in_array() function to check if a value exists in an array.
Introduction to the PHP in_array() function
The in_array() function returns true if a value exists in an array. Here’s the syntax of the in_array() function:
in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool
Code language: PHP (php)- $needle is the searched value.
- $haystack is the array to search.
- $strict if the $strict sets to true , the in_array() function will use the strict comparison.
The in_array() function searches for the $needle in the $haystack using the loose comparison ( == ). To use the strict comparison ( === ), you need to set the $strict argument to true .
If the value to check is a string, the in_array() function will search for it case-sensitively.
The in_array() function returns true if the $needle exists in the $array ; otherwise, it returns false .
PHP in_array() function examples
Let’s take some examples of using the in_array() function.
1) Simple PHP in_array() function examples
The following example uses the in_array() function to check if the value ‘update’ is in the $actions array:
$actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('update', $actions); var_dump($result); // bool(true)
Code language: HTML, XML (xml)The following example returns false because the publish value doesn’t exist in the $actions array:
$actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('publish', $actions); var_dump($result); // bool(false)
Code language: HTML, XML (xml)The following example returns false because the value ‘New’ doesn’t exist in the $actions array. Note that the in_array() compares the strings case-sensitively:
$actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('New', $actions); var_dump($result); // bool(false)
Code language: HTML, XML (xml)2) Using PHP in_array() function with the strict comparison example
The following example uses the in_array() function to find the number 15 in the $user_ids array. It returns true because the in_array() function compares the values using the loose comparison ( == ):
$user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids); var_dump($result); // bool(true)
Code language: HTML, XML (xml)To use the strict comparison, you pass false to the third argument ( $strict ) of the in_array() function as follows:
$user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids, true); var_dump($result); // bool(false)
Code language: HTML, XML (xml)This time the in_array() function returns false instead.
3) Using PHP in_array() function with the searched value is an array example
The following example uses the in_array() function with the searched value is an array:
$colors = [ ['red', 'green', 'blue'], ['cyan', 'magenta', 'yellow', 'black'], ['hue', 'saturation', 'lightness'] ]; if (in_array(['red', 'green', 'blue'], $colors)) < echo 'RGB colors found'; > else < echo 'RGB colors are not found'; >
Code language: HTML, XML (xml)4) Using PHP in_array() function with an array of objects example
The following defines the Role class that has two properties $id and $name :
class Role < private $id; private $name; public function __construct($id, $name) < $this->id = $id; $this->name = $name; > >
Code language: HTML, XML (xml)This example illustrates how to use the in_array() function to check if a Role object exists in an array of Role objects:
// Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles)) < echo 'found it'; >
Code language: HTML, XML (xml)If you set the $strict to true , the in_array() function will compare objects using their identities instead of values. For example:
// Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles, true)) < echo 'found it!'; > else < echo 'not found!'; >
Code language: PHP (php)Summary