When you need the position of each item in a loop, counting from 0 to the length goes wrong as soon as the array has a hole in it. Bash can give you the real indexes.
Put ! in front of the array name:
hosts=(web db cache)
unset 'hosts[1]'
echo "${!hosts[@]}" # 0 2
echo "${#hosts[@]}" # 2
After the unset there are two elements, at positions 0 and 2. A loop from 0 to 1 would hit the missing one and skip cache. Looping over the indexes is safe:
for i in "${!hosts[@]}"; do
echo "$i: ${hosts[i]}"
done
For an associative array made with declare -A, the same syntax gives you the keys, which is how you walk through a lookup table.
The keys of an associative array come back in no particular order, so sort them if the order matters. If you want a gap-free array again, copy it into itself with hosts=("${hosts[@]}"). I like that better than keeping a separate counter. Also note the quotes around 'hosts[1]' in the unset: without them, a file called hosts1 in the current folder could turn the brackets into a glob.
Further reading: Bash manual: Arrays