PHP Array Search Key
To check a key of an array exists or not we use array_key_exists(). The function returns Boolean value that indicates that whether the given key exists within the array or not. If the key exists in the array it returns True or the function returns false.
General description of array_key_exists() is:
| General Format | boolean array_key_exists(mixed $key, array $array) | |
| Parameters | mixed $key: key to check
|
array $array: the array to be checked |
| Return Value | Boolean value: True/False | |
PHP Array Search Key Example 1:
<?php
$array1=array("a"=>1,"b"=>2,"c"=>3); echo"<br/><b>Initially the values of \$array1 is:</b><br/>";var_dump(
$array1); $key="c"; echo"<br/><b>The key is:$key</b><br/>"; if(array_key_exists($key,$array1)) echo"<br/><b>Found</b><br/>"; elseecho
"<br/><b>Not Found</b><br/>";?>
Output:
Initially the values of $array1 is:
array(3) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
}
The key is:c
Found
Example 2:
<?php
$array1=array("b"=>array("x"=>"beneath","y"=>"benign"),"c"=>"contemporary","d"=>"diligent"); echo"<br/><b>Initially the values of \$array1 is:</b><br/>";var_dump(
$array1); $key="x"; echo"<br/><b>The key is:$key</b><br/>"; if(array_key_exists($key,$array1)) echo"<br/><b>Found</b><br/>"; elseecho
"<br/><b>Not Found</b><br/>"; $key="c"; echo"<br/><b>New key is:$key</b><br/>"; if(array_key_exists($key,$array1)) echo"<br/><b>Found</b><br/>"; elseecho
"<br/><b>Not Found</b><br/>";?>
Output:
Initially the values of $array1 is:
array(3) {
["b"]=>
array(2) {
["x"]=>
string(7) "beneath"
["y"]=>
string(6) "benign"
}
["c"]=>
string(12) "contemporary"
["d"]=>
string(8) "diligent"
}
The key is:x
Not Found
New key is:c
Found
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.