Is there any PHP function to perform in_array()
for associative array? I know how to do with a foreach
loop, but is there a PHP function or more elegant way to do this?
Both in_array()
and array_search()
work just fine for associative arrays.
See these examples:
php > $array = ['one' => 1, 'two' => 2, 'three' => 3];
php > var_dump(in_array(2, $array));
bool(true)
php > var_dump(in_array(5, $array));
bool(false)
php > var_dump(array_search(2, $array));
string(3) "two"
php > var_dump(array_search(5, $array));
bool(false)
in_array() function is utilized to determine if specific value exists in an array.
It works fine for one dimensional numeric and associative arrays.
Please refer the following example code snippet which depicts the use of in_array function to check existence of value in an associative array.
$a=array();
$a['id']=1;
$a['name']='James';
$result=in_array('James',$a);
var_dump($result);