Tuesday 10 March 2015

Difference between in_array and array_key_exists in php with example

Difference between in_array and array_key_exists in php with example

in_array: Checks if a value exists in an array OR not.
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] );

Parameters
needle: The searched value.
haystack: The array.
strict: If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return: Returns TRUE if needle is found in the array, FALSE otherwise.

Example:
$array = array("Web", "Technology", "Experts", "Notes");
if (in_array("Technology", $array)) {
    echo "Record Found in value";
}



array_key_exists: Checks if the given key/index exists in the array.
bool array_key_exists ( mixed $key , array $array );
Parameters key: Value to check.
array: An array with keys to check.

Return: Returns TRUE on success or FALSE on failure.

Example:
$searchArray = array('Web' => 1, 'Technology' => 4);
if (array_key_exists('Web', $searchArray)) {
    echo "Record Found in key";
}