Description
array_key_exists()
: check if key exists into array!
Equivalent to the PHP Function PHP array_key_exists()
Source Code
Code: bash
function array_key_exists() {
# equivalent to PHP array_key_exists
# call: array_key_exists key array
local key="$1" IFS=" "; shift; read -a array <<< "$@"
if [[ "${array[$key]}" ]]; then return 0; else return 1; fi
unset array key IFS
}
Parameters
key
is the searched keyhaystack
is the array where to search
Return Values
- Returns
0
if thekey
found intohaystack
; considere this value asTRUE
- Otherwise, returns
1
: considere this value asFALSE
Example
Code: bash
declare -a color=("blue", "red", "green", "grey");
key=1
if array_key_exists "${key}" "${color[@]}"; then
echo "key: ${key} exists!"
else
echo "This key: ${key} not exists!"
fi