# Getting last value in tikz foreach

I tried this, but it doesn't work as intended:

\foreach \x/\index in {4/0,5/1,19/2} {
\ifnum \index > 0
% use lastx
\fi
\pgfmathsetmacro\lastx{\x}
}


How do I set \lastx properly?

-

You can use the additional facilities of foreach macro given in the manual by adding pgfmath package too. For some reason, (initially 4) option is not working if TikZ is not fully loaded so you can define it externally.

\documentclass{article}
\usepackage{pgffor,pgfmath}
\begin{document}
\def\lastx{4}
\foreach \x[count=\xi from 2,remember=\x as \lastx] in {5,19,20,25} {
This variable \x, the value before was \lastx\space  and it is the argument \xi\space in the list.\par
}

\end{document}


-

Assignments in a \foreach are local, so you can use \xdef\lastx{\x}:

## Code:

\documentclass{article}
\usepackage{pgffor}

\newcommand*{\lastx}{}

\begin{document}
\foreach \x/\index in {4/0,5/1,19/2} {
\ifnum \index > 0
% use lastx
\fi
\xdef\lastx{\x}
}

Last x was \lastx
\end{document}

-