# Define newcommand inside a loop

In my latex document I have defined an array of element and I am making a loop within this array. I would like to define newcommand inside this loop. The idea is to make

\newcommand{\name1}{
\begin{center}
\scshape{name1}
\end{center}
}

\newcommand{\name2}{
\begin{center}
\scshape{name2}
\end{center}
}

\newcommand{\name3}{
\begin{center}
\scshape{name3}
\end{center}
}


What I did is:

\usepackage{pgffor}
\def \peopleArray {name1, name2, name3}
\foreach \x in \peopleArray {
\newcommand{\x}{
\begin{center}
\scshape{name3}
\end{center}
}
}


but this won't work.

I have also tried this

\foreach \x in \peopleArray {%
\expandafter\xdef\csname \x\endcsname{\begin{center}
\scshape{x}
\end{center}}
}


but this doesn't work either

• It would be nice if you could give a simple compilable example... notice however that numbers can't be part of a LaTeX macro name (although you can do tricks, see for example package etoolbox, maybe \csuse and company can help you), and then, \scshape is a switch, so you should use {\scshape wwhatever}. Jul 26 at 16:37
• In addition to what @Rmano says, each cycle in a \foreach loop is executed in a group, so the \newcommand will be lost. Jul 26 at 16:47
• @Rmano well, the code won't have any number in it. I just used them for the sake of the example. What I don't understand in your comment is: so it is not possible? Jul 26 at 16:51
• @FabienneLablatte Perhaps it's better that you make a more “real world” example, then. Jul 26 at 16:52

Here's one way to define a sequence of macros with a for loop, with an example of usage:

\documentclass{article}
\usepackage{pgffor}
\def \peopleArray {\nameA, \nameB, \nameC}
\begin{document}
\foreach \x in \peopleArray {
\expandafter\gdef\x{
\begin{center}
{\scshape name3}
\end{center}
}
}
\nameA
\nameB
\nameC
\end{document}


I had to use \gdef instead of \newcommand because otherwise the definition is local (and lost) instead of global.

I'm not sure this is useful though, because name3 is the same in all cases.

• you should add \newcommand so that you get a error if you overwrite an existing command. Jul 26 at 18:19
• @UlrikeFischer How would you make the \newcommand global? Jul 26 at 18:29
• you don't have to, you can use \newcommand to test and then \gdef Jul 26 at 18:32