'pgfmathresult' uses the argument for 'text opacity'

The issue is that \pgfmathresult gets overwritten, so you may want to use \pgfmathsetmacro instead to store the result of the computation in a macro. (I also got rid of xifthen because it is not needed for integer comparisons, for which you can use a simple \ifnum.)

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{backgrounds}
\begin{document}
    \begin{tikzpicture}
        [
          every label/.style={inner sep=0pt, opacity=0.8, text opacity=1.0, fill=white},
          cnode/.style={draw=black,fill=#1,minimum width=3mm,circle},
        ]
        \node[cnode=red,label=0:{$\hat y_1$}] (s1) at (6,-1) {};
        \node[cnode=red,label=0:{$\hat y_2$}] (s2) at (6,-2) {};
        \node at (6,-3) {$\vdots$};
        \node[cnode=red,label=0:{$\hat y_K$}] (sK) at (6,-4) {};

        \foreach \x in {0,...,4}
        {   
            \pgfmathsetmacro{\myindex}{\x<4 ? \x : "q-1"}
            \ifnum\x>0
                \node[cnode=gray,label={90:$z_{\myindex}$}] (h-\x) at (3,{-\x-div(\x,4)+.5}) {};
            \else
                 \node[cnode=gray,label=90:$1$] (h-0) at (3,0.5) {};
            \fi
            \begin{scope}[on background layer]
              \draw (h-\x) --  (s1);
            \draw (h-\x) -- (s2);
            \draw (h-\x) --  (sK);
            \end{scope}
        }

        \node at (3,-3.5) {$\vdots$};

        \node[cnode=gray,label=90:$z_{M}$] (h-q) at (3,-5.5) {};
        \begin{scope}[on background layer]
        \draw (h-q) --  (s1);
        \draw (h-q) -- (s2);
        \draw (h-q) --  (sK);
        \end{scope}
    \end{tikzpicture}
\end{document}

enter image description here