How to check whether a zsh array contains a given value

zsh

Suppose I have a non-associative array that has been defined like

my_array=(foo bar baz)

How can I check whether the array contains a given string? I’d prefer a solution that can be used within the conditional of an if block (e.g. if contains $my_array "something"; then ...).

Best Answer

array=(foo bar baz foo)
pattern=f*
value=foo

if (($array[(I)$pattern])); then
  echo array contains at least one value that matches the pattern
fi

if (($array[(Ie)$value])); then
  echo value is amongst the values of the array
fi

$array[(I)foo] returns the index of the last occurrence of foo in $array and 0 if not found. The e flag is for it to be an exact match instead of a pattern match.

To check the $value is among a literal list of values, you could pass that list of values to an anonymous function and look for the $value in $@ in the body of the function:

if ()(( $@[(Ie)$value] )) foo bar baz and some more; then
  echo "It's one of those"
fi

To know how many times the value is found in the array, you could use the ${A:*B} operator (elements of array A that are also in array B):

array=(foo bar baz foo)
value=foo
search=("$value")
(){print -r $# occurrence${2+s} of $value in array} "${(@)array:*search}"
Related Question