Process Last Item in \ForEach (forarray package)

The following command of the forarray package

\ForEach{,}{\thislevelitem(\the\thislevelcount) : }}{x,y,z}


produces the output

x(1) : y(2) : z(3) :


I want to have the same output without the last ":".

The forarray package does not provide any command like \maxount to test if \thislevelcount == \maxcount. Surly I could test for the first item \thislevelcount == 0 but what to do if this cannot be done for some reason?

How can I process the last item separately if the number of items is variable/unknown?

-

You can cheat and prepend : to all the items except for the first

\documentclass{article}
\usepackage{forarray}
\begin{document}
\ForEach{,}{\ifnum\thislevelcount=1\else : \fi\thislevelitem(\the\thislevelcount)}{x,y,z}
\end{document}


or you can use the totcount package to get the number of items in the array

\documentclass{article}
\usepackage{forarray}
\usepackage{totcount}
\begin{document}
\newtotcounter{myarray}
\ForEach{,}{\stepcounter{myarray}\thislevelitem(\the\thislevelcount)\ifnum\thislevelcount=\totvalue{myarray}\else : \fi}{x,y,z}
\end{document}

-
The first is okay but it’s not the last item. However, I used the first item solution (as mentioned in my question). I do not understand the second solution. How does the totcount package know the number of total items in your example? –  Ronny Jun 12 '12 at 12:06
@Ronny knowing the total number of items is the magic of the totcount package. Basically the package requires two passes. On the first pass it writes the final value of the counter to the aux file and on the second pass it reads the value. –  StrongBad Jun 12 '12 at 13:09
Good to know, thanks! –  Ronny Jun 12 '12 at 13:54

You can also use the \indrisloop macro of the catoptions package.

\documentclass{article}
\usepackage{catoptions}
\begin{document}
\def\do#1{%
#1(\indrisnr)\space\iflastindris\else:\space\fi
}
\indrisloop{x,y,x}\do
\end{document}


-

Similar to my comments in pgffor: Special treatment for last item in \foreach-list the other answers here provide solutions to accomplish the task at hand, but don't address the problem in the title of the question.

One way to detect the last list member and treat it differently is to count the number of members at the start of the list processing and compare that to \the\thislevelcount to know when we have come to the last one:

Code:

\documentclass{article}
\usepackage{forarray}
\usepackage{xstring}

\newcounter{TotalNumberOfListMembers}%
\newcommand{\SetTotalNumberOfListMembers}[1]{%
\setcounter{TotalNumberOfListMembers}{0}%
\ForEach{,}{\stepcounter{TotalNumberOfListMembers}}{#1}%
}%

\newcommand*{\ProcessListMembers}[1]{%
\SetTotalNumberOfListMembers{#1}
\ForEach{,}{%
\thislevelitem(\the\thislevelcount)%
\IfEq{\the\thislevelcount}{\the\value{TotalNumberOfListMembers}}{}{: }%
}{#1}%
}%

\begin{document}
\ProcessListMembers{x,y,z}
\end{document}

-