# Ending a tikzpicture environment in conditional causes “Missing } inserted”

I want to create a number of tikzpictures. I have a number of items I want to draw. Each tikzpicture takes up a whole page and may contain up to 4 items. (It is not good enough to to have each item in its own tikzpicture.) So if there are 16 items, I will need 4 tikzpictures, but if there are 17 I will need 5. I thought I could loop over the items in the list using a counter and begin and end tikzpictures at the appropriate points (and end any open tikzpicture at the end if the last one is not full up). But it doesn't work. If I hit the end{tikzpicture} at the end of the loop then I get Missing } inserted. I anticipate this has something to do with TeX groups, but I do not know how to work with environments in a way that gets around groups.

Here is a minimal example.

\documentclass{minimal}

\usepackage{tikz}

\newcounter{mycounter}

\def\iteration{%
\stepcounter{mycounter}%
\ifnum5=\value{mycounter}%
\setcounter{mycounter}{1}%
\begin{tikzpicture}%
\fi%
\draw (0, 0) -- (1, 0);%
\ifnum4=\value{mycounter}%
\end{tikzpicture}%
\fi%
}

\begin{document}%
\setcounter{mycounter}{4}%
\foreach \x in {1, 2, 3, 4, 5, 6} {\iteration}%
\ifnum4>\value{mycounter}%
\end{tikzpicture}%
\fi%
\end{document}

• Why not looping inside a tikzpicture? \foreach starts the TikZ in a group. But tries to end in a different one as is. – percusse Apr 4 '15 at 18:27
• @percusse But tikzpicture cannot break across pages, can it? – cfr Apr 4 '15 at 18:35
• @cfr It still won't even if this would work. – percusse Apr 4 '15 at 18:38
• This works for me: \begin{document}\setcounter{mycounter}{4}\ifnum4>\value{mycounter}\expandafter\endtikzpicture\fi \end{document} But not inside the loop – Yossi Gil Apr 4 '15 at 19:17
• I went about it another way by constructing a list of lists instead of just a single-level list. – Hammerite Apr 4 '15 at 23:00