php проверить есть ли ключ в массиве

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс

Описание

Список параметров

Массив с проверяемыми ключами.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

array_key_exists() ищет ключи только на первом уровне массива. Внутренние ключи в многомерных массивах найдены не будут.

Примеры

Пример #1 Пример использования array_key_exists()

Пример #2 array_key_exists() и isset()

Примечания

Смотрите также

User Contributed Notes 39 notes

If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:

Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms

Note:
The code for this check is very fast, so you shouldn’t warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.

function array_check(. )
<
return (isset(..) || array_key_exists(. ))
>

You’ll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.

= array();
$foo [ ‘bar’ ] = NULL ;

Beware that if the array passed to array_key_exists is NULL, the return value will also be NULL.

This is undocumented behaviour, moreover the documentation (and return typehint) suggest that the array_key_exists function only returns boolean value. But that’s not the case.

Rudi’s multidimensional array_key_exists function was not working for me, so i built one that is.
Enjoy.

The way array_key_exists handles null, float, boolean, and ‘integer-representing string’ keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.

array (
» => 1,
0 => 2,
1 => 3,
4 => 4,
’08’ => 5,
8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
«08» is a key.
«8» is a key.

Well, and you get this warning three times (on the bools and the float, but not on the null):

Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6

I’ve got a new take on the multi key function I would like to share.

Very simple case-insensitive array_key_exists:

bool (in_array(strtolower($needle), array_map(‘strtolower’, array_keys($haystack))))

array_key_exists doesn’t work with objects implementing ArrayAccess interface. It also ignores possible __get() method in such objects, despite the fact it accepts object as a second parameter. It works only with ‘real’ properties.

Here is an example with array_key_exists switching between content-types :

The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:

?>

On Windows, the output is similar to

array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds

On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.

Источник

Использование функций isset() и array_key_exists()

Навеяно проблемой, с которой я столкнулся из-за неправильного использования функции isset() в одном китайском движке интернет магазина. Там isset() применялась для определения существования элемента массива с некоторым ключом. Самое неприятное в данной ситуации то, что такую ошибку допускают многие. Это не первый случай, когда isset() используется именно в таком контексте, хотя это в корне неверно. Но в этот раз неграмотность разработчиков стоила мне потерянного времени, что и сподвигло меня на эту заметку.

Собственно, об уровне квалификации PHP программистов сказано немало и добавить к этому нечего.

Инициализация и удаление переменной в PHP

В PHP переменная инициализируется в момент присваивания ей значения. Неинициализированной переменная считается в двух случаях:

Функция isset()

Функция проверяет факт инициализации переменной. isset() вернет false, если передать ей в качестве параметра неинициализированную переменную. Тоже самое произойдет и с ключом массива, который имеет NULL значение. Для ключей массива действуют такие же правила приведения к NULL, как и для переменных.

Результат:

Функция array_key_exists()

Для массива использование NULL значения ключа удобно, если наличие ключа требуется сохранить. Можно будет рассчитывать на контекст, в котором данный ключ будет использован. Например, это удобно при заполнении полей формы дефолтными значениями. Например, при использовании конструкции echo, NULL значение будет приведено к пустой строке.

То, к чему я клоню, мне кажется очевидным. Если вы работаете с ключами массива, то используйте именно ту функцию, которая для этого предназначена. Ко всему прочему, использование array_key_exists() позволяет точно понять логику приложения. Никакой двусмысленности не возникает.

Скорость работы isset() и array_key_exists()

О том, что array_key_exists() работает медленнее isset() пишут даже в комментариях к соответствующей странице PHP мануала. Жалуются на то, что более медленная работа array_key_exists() заметна на массивах с количеством пар ключ-значение, превышающих 200.

Ничего не остается, как прогнать банальный тест:

isset()array_key_exists()
0.6870270.728652

Тест, безусловно, очень простой и достаточно субъективный. Было бы неплохо сделать замеры используемой памяти, например. Но глядя на результаты этого теста, у меня нет никакого желания продолжать заниматься мышиной возней. Очевидно, что выигрыша в скорости попросту нет.

Функция isset() и свойства объекта

Совсем клиническим случаем можно считать использование isset() для проверки существования свойства у объекта.

Не так часто, как в случае с массивами, но доводится встречать подобные условия:

Случай вопиющий, так как использование NULL в качестве дефолтного значения свойств – очень распространенная практика. И проверять наличие свойства объекта через isset() просто недопустимо.

Также замечу, что для использования property_exists() не требуется наличие объекта класса. Проверку можно произвести по имени класса и имени свойства.

Такое вот занимательное программирование.

Комментарии (6)

Вечер добрый!
Очень классные статьи, большое спасибо за них!

Вы все верно поняли. На самом деле, практически повсеместно используется isset(). Иногда из-за этого возникают логические ошибки в приложениях, что и стало причиной написания данной заметки.

Не надо людей вводить в заблуждение и навязывать свои ошибочные мысли.
В мануале от создателей PHP явно сказано, что isset используется и для проверки элементов массива.
И это правильно. А вот использовать элемент массива с NULL и считать этот элемент существующим, это ошибка.
Вот из-за таких как ты и приходится потом сутками сидеть и разгребать больные коды и не понимать, почему же блин переменные NULL существуют.

Максим, во-первых, я вам вам не «ты». А во-вторых, мир сложнее, чем вам кажется и нужно беречь свои нервы, а то не хватит сил на разгребание больных кодов :))
И если NULL значение в массиве — это ошибка, то это ошибка в интерпретаторе PHP. Но, думаю, дело все в том, что вы просто не понимаете смысл типа данных NULL.

Олег, вы не правы в ряде моментов. Не стоит «гнать» на PHP разработчиков, т.к. те кто ними являются, пишут хороший код. А то, что вы всех, кто написал строчку кода на PHP называете PHP-программистом, это лично ваши «психо-половые» проблемы. Второй момент, насчет NULL: в языке PHP смысл языковой конструкции null отличается от той же конструкции SQL … и не стоит и пытаться друг на друга «натягивать». Это не проблема языка, т.к. авторы языка вольны толковать как им вздумается «сколько людей, столько и мнений.». Третий момент, если Вы знаете, что PHP-разработчики пишут плохой код, то зачем вы его используете? Пишите сами или используете код других языков. Я могу понять, что писали вы пост под влиянием эмоций, но я так и не понял, что было не так в том коде «китайского движка» и что у вас не выходило? 🙂 Напишите название движка, чтобы люди знали о том, и что тут могут вылезти проблемы при использовании и место возникновения проблемы.

На 100 000 итерации isset работает в 6 раз быстрее.

Источник

array_keys

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

array_keys — Возвращает все или некоторое подмножество ключей массива

Описание

Список параметров

Массив, содержащий возвращаемые ключи.

Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.

Определяет использование строгой проверки на равенство (===) при поиске.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_keys()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 28 notes

It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

?>

will return on a 64 bits system:

but on a 32 bits system:

I hope it will save someone the huge headache I had 🙂

Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.

Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );

But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:

echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );

However I would expect in time the PHP team will modify the rules of parentheses.

There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.

Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.

NOTE: If the sub element isn’t an array, it will be ignore.

output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)

array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0

—-
expected to see:
dude dude dude

Sorry for my english.

I wrote a function to get keys of arrays recursivelly.

Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

?>

Example usage (pseudo-database code):

= db_query ( ‘SELECT name, value FROM properties’ );

/* This will return an array like so:

/* Now this array looks like:

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.

An alternative to RQuadling at GMail dot com’s array_remove() function:

The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».

Hope this helps someone.

# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:

Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)

This function will extract keys from a multidimensional array

Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)

[size] => Array
(
[0] => small
[1] => medium
[2] => large
)

Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)

All the cool notes are gone from the site.

Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

Simple ways to prefixing arrays;

[1] => Array
(
[product_id] => 2
[product_name] => Bar
)

I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

A needed a function to find the keys which contain part of a string, not equalling a string.

Источник

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_search — Осуществляет поиск данного значения в массиве и возвращает ключ первого найденного элемента в случае успешного выполнения

Описание

Список параметров

Если needle является строкой, сравнение происходит с учётом регистра.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_search()

Смотрите также

User Contributed Notes 44 notes

in (PHP 5 >= 5.5.0) you don’t have to write your own function to search through a multi dimensional array

$userdb=Array
(
(0) => Array
(
(uid) => ‘100’,
(name) => ‘Sandra Shush’,
(url) => ‘urlof100’
),

(1) => Array
(
(uid) => ‘5465’,
(name) => ‘Stefanie Mcmohn’,
(pic_square) => ‘urlof100’
),

(2) => Array
(
(uid) => ‘40489’,
(name) => ‘Michael’,
(pic_square) => ‘urlof40489’
)
);

simply u can use this

$key = array_search(40489, array_column($userdb, ‘uid’));

About searcing in multi-dimentional arrays; two notes on «xfoxawy at gmail dot com»;

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you’d expect.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn’t call array_column() for each element it searches. For a better performance, you could do;

It’s what the document stated «may also return a non-Boolean value which evaluates to FALSE.»

the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don’t know what I’m talking about, here’s an example:

hallo every body This function matches two arrays like
search an array like another or not array_match which can match

for searching case insensitive better this:

About searcing in multi-dimentional arrays;
note on «xfoxawy at gmail dot com» and turabgarip at gmail dot com;

$xx = array_column($array, ‘NAME’, ‘ID’);
will produce an array like :
$xx = [
[ID_val] => NAME_val
[ID_val] => NAME_val
]

$yy = array_search(‘tesxt’, array_column($array, ‘NAME’, ‘ID’));
will output expected ID;

To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()

Be careful when search for indexes from array_keys() if you have a mixed associative array it will return both strings and integers resulting in comparison errors

/* The above prints this, as you can see we have mixed keys
array(3) <
[0]=>
int(0)
[1]=>
string(3) «car»
[2]=>
int(1)
>
*/

hey i have a easy multidimensional array search function

Despite PHP’s amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

But again, with the above solution, PHP again falls short on how to dynamically access a specific element’s value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

I needed a way to return the value of a single specific key, thus:

Better solution of multidimensional searching.

FYI, remember that strict mode is something that might save you hours.

one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. (or even a string that looks like a number)

The problem is that unless you specify «strict» the match is done using == and in that case any string will match a numeric value of zero which is not what you want.

also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

//very fast lookup, this beats any other kind of search

I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

A simple recursive array_search function :

A variation of previous searches that returns an array of keys that match the given value:

I needed a function, that returns a value by specifying a keymap to the searched value in a multidimensional array and came up with this.

My function get_key_in_array() needed some improvement:

An implementation of a search function that uses a callback, to allow searching for objects of arbitrary complexity:

For instance, if you have an array of objects with an id property, you could search for the object with a specific id like this:

For a more complex example, this function takes an array of key/value pairs and returns the key for the first item in the array that has all those properties with the same values.

The final step is a function that returns the item, rather than its key, or null if no match found:

Источник

Как проверить, существует ли несколько ключей массива

у меня есть множество массивов, которые будут либо содержать

как бы я проверил, содержит ли массив историю и сообщение? array_key_exists() ищет только один ключ в массиве.

есть ли способ сделать это?

18 ответов

Если у вас есть только 2 ключа для проверки (как в исходном вопросе), это, наверное, достаточно просто позвонить array_key_exists() дважды, чтобы проверить, существуют ли ключи.

однако это, очевидно, не масштабируется до многих ключей. В этой ситуации поможет пользовательская функция.

вот решение, которое масштабируется, даже если вы хотите проверить наличие большого количества ключей:

неожиданно array_keys_exist не существует?! В промежутке это оставляет некоторое пространство, чтобы выяснить одно строчное выражение для этой общей задачи. Я думаю о сценарии оболочки или другой небольшой программе.

Примечание: каждое из следующих решений использует краткий […] синтаксис объявления массива доступен в php 5.4+

array_diff + array_keys

(наконечник шляпы к Ким Стеки)

array_reduce + unset

конструкция легка для того чтобы доработать в виду того что ключи мы заинтересованы в пригонке славно на нижней строке.

array_filter & in_array

проще написать, чем array_reduce решение, но немного сложнее редактировать. array_filter также является итеративным обратным вызовом, который позволяет создавать отфильтрованный массив, возвращая true (копировать элемент в новый массив) или false (не копировать) в обратном вызове. В gotchya, что вы должны изменить 2 к числу элементов, которые вы ожидаете.

это можно сделать более прочным, но verge на нелепой читаемости:

мне кажется, что самым простым методом было бы следующее:

Это также позволяет проверить, какие ключи отсутствуют точно. Это может быть полезно для обработки ошибок.

вышеуказанные решения умны, но очень медленны. Простой цикл foreach с isset более чем в два раза быстрее array_intersect_key решение.

(344ms против 768ms для 1000000 итераций)

только верните true, если оба не null

Если равно null, ключ не находится в array

если у вас есть что-то вроде этого:

вы могли бы просто count() :

это работает, только если вы точно знаете, что у вас есть только эти ключи массива, и ничего больше.

использование array_key_exists () поддерживает только проверку одного ключа за раз, поэтому вам нужно будет проверить оба отдельно:

array_key_exists() возвращает true, если ключ присутствует в массиве, но это реальная функция и тип. Язык построить isset() будет почти делать то же самое, за исключением того, если тестируемое значение равно NULL:

дополнительно isset позволяет проверить сразу несколько переменных:

теперь, чтобы оптимизировать тест для вещей, которые установлены, вам лучше использовать это «если»:

еще одно решение в коллекции:

Это функция, которую я написал для себя, чтобы использовать в классе.

Я предполагаю,что вам нужно проверить наличие нескольких ключей в массиве. Если вы ищете совпадение хотя бы одного ключа, дайте мне знать, чтобы я мог предоставить другую функцию.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *