%

Bash : function array_search()

Function bash array_search(), equivalent to PHP

Details about this article

Article published the
; modified the
One minute to read

This article has 120 words.

Uniq IDentifiant: tag:doc.huc.fr.eu.org,2017-07-29:/en/dev/bash/function-array-search


RAW source of the article:
Commit version: 9bf3d7b


This article is also available on Gemini Protocol:
gemini://gmi.it-log.fr.eu.org/en/dev/bash/function-array-search.gmi


Description

array_search(): Searches the array for a given value and returns the corresponding key if successful

Equivalent to the PHP array_search function.

Source Code

function array_search() {

    # equivalent to PHP array_search
    # call: array_search needle array

    local needle="$1" IFS=" "; shift; read -a array <<< "$@"

    for (( i=0; i < ${#array[*]}; i++ )); do
        if [[ "${array[$i]}" == "${needle}" ]]; then echo "$i"; fi
    done
    return 1

    unset array needle IFS

}

Parameters

  • needle is the searched value
  • haystack is the array where to search

Return Values

  • Returns the key for needle, if is found into the array haystack
  • Otherwise, returns 1: considere this value as FALSE.

Example

declare -a color=("blue", "red", "green", "grey");
echo "$(array_search "red" "${color[@]}")"


Enjoy-ID!
Enjoy-IT!