%

Bash: function array_key_exists()

Article published the ; modified the
One minute to read

This article has 119 words.
RAW source of the article:
Commit version: e21600e

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 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