What is the difference between in_array() and array_key_exists()?

In array search in values of arary while array_key_exist() check key is exist and return like

$arr=["a"=>1,"b"=>2,"c"=>3,4,5,6];
// now you need to search 5 in $arr then you need to use  in_array()
// and array_key_exists() check if key exist in array 
in_array(5);  //return true
array_key_exist("a"); // return true

in_array() versusarray_key_exists()

Difference:

  • in_array() checks if a value exists in an array (checks the values, not the keys) and returns true, or false otherwise.

while:

  • array_key_exists() checks if the given key or index exists in the array (checks in keys, not in values) and returns true, or false otherwise.

Visits the manual (links above) for examples and more information.

An example link: https://eval.in/602279


Just my two cents:

First in_array will check the existance of the given parameter among an array values, meaning that it will ignore the array keys if searching against an associative array.

Second in_array accepts a third parameter (TRUE or FALSE, FALSE by default) to use strict type comparison. If you omit this parameter, it will happen that:

in_array(0,[false]) => true (0 is coerced to boolean for loose comparison)
in_array(1,['1 person']) => true ('1 person' is coerced as numeric until the first non numeric character)
in_array('',[null]) => true (again, string is coerced).

Third You can check if an array contains another array:

in_array([1,2],[[1,2], [3,4]]) => true

Fourth array_key_exists will search among the array keys. If the array is non associative, the numeric index of each element is the key:

array_key_exists(0,[1,2,3]) => true (there is an element at index 0)

However, the usual case is to search for a string key:

array_key_exists('two',['one'=>1, 'two'=>2]) => true (there is an element with key 'two')

The comparison is not really strict, meaning that

array_key_exists(0,['0'=>1, 'two'=>2]) => true

But this is explained in the documentation. Array keys are coerced to numeric if they are either strings containing only numbers (optionally, with a decimal separator), boolean or float numbers. NULL is casted to an empty string. So the keys might be either integers or strings. Aside from that implicit conversion, the following is false:

array_key_exists(1,['1 person'=>1, 'two'=>2]) => false

Finally, in_array performs a sequential scan on the array contents, whereas array_key_exists performs a search against a hash table. This means the performance of the latter is constant no matter the size of the array you're searching, whereas in_array speed is proportional to the array size. So if you're doing

in_array('one', array_keys(['one'=>1, 'two'=>2]))

You really really should be doing

array_key_exists('one', ['one'=>1, 'two'=>2])

Tags:

Php

Arrays