Bash: function array_key_exists()

Article published the
1 minute(s) to read

This article has 116 words.
RAW source of the article: MD

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; return 1; if

   unset array key IFS

}

Parameters

  • key is the searched key
  • haystack is the array where to search

Return Values

  • Returns 0 if the key found into haystack; considere this value as TRUE
  • Otherwise, returns 1: considere this value as FALSE

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