Counting lines in a loop and getting zero at the end is a classic.
count=0
while read -r line; do count=$((count+1)); done < <(ls /etc)
echo "$count"
In cmd | while read ... the loop runs in a subshell, so variables set inside are gone after done. Process substitution < <(cmd) keeps the loop in the main shell and only runs the command in the background. Note the space between the two < signs. It is a bash and zsh feature, not available in plain sh. In bash you can also use shopt -s lastpipe for scripts.
Further reading: Bash manual: Process Substitution