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
needleis the searched valuehaystackis the array where to search
Return Values
- Returns the key for
needle, if is found into the arrayhaystack - Otherwise, returns
1: considere this value asFALSE.
Example
declare -a color=("blue", "red", "green", "grey");
echo "$(array_search "red" "${color[@]}")"