Newcommand options and for each
The problem is unrelated to foreach
you would see the same from \def\x{1} \case{\x}
You are comparing \ifx 1\x
and the tokens 1 and \x
are not the same so this is false.
Conversely \case{12}
would test \ifx112
which would test 1 and 1 as true and then typeset 2.
You want to do a numeric test not test the unexpanded tokens, so
\documentclass{article}
\newcommand\case[1]{%
\ifcase\numexpr#1\relax
case 0\or
case 1\or
case 2\or
case 3\else
Illegal%
\fi}
\usepackage{tikz}
\begin{document}
\case{1}
\case{12}
\case{3}
\foreach \x in {1,2,3}{\case{\x}}
\end{document}
I can propose a more flexible set of commands.
\documentclass{article}
\usepackage{pgffor}
%\usepackage{xparse} % uncomment if using LaTeX released before 2020-10-01
\ExplSyntaxOn
\NewExpandableDocumentCommand{\checkcases}{mmO{}m}
{
\int_case:nnTF { #1 } { #2 } { #3 } { #4 }
}
\ExplSyntaxOff
\newcommand{\mycaseswitch}[1]{%
\checkcases{#1}{
{1}{Case 1}
{2}{Case 2}
{3}{Case 3}
{42}{Ultimate}
}{Illegal}%
}
\newcommand{\otherswitch}[1]{%
\checkcases{#1}{
{-2}{Negative}
{2}{Positive}
}[!]{Bad?}%
}
\begin{document}
\mycaseswitch{1}: case 1
\mycaseswitch{2}: case 2
\mycaseswitch{3}: case 3
\mycaseswitch{4}: illegal
\mycaseswitch{42}: Hey!
\foreach \x in {1,2,3}{\mycaseswitch{\x}\par}
\otherswitch{-2}
\otherswitch{2}
\otherswitch{0}
\end{document}
The \checkcases
command is just an interface to the internal expl3
function \int_case:nnTF
. It has four arguments:
- the integer to test against the case list;
- the case list, in the form of pairs
{<integer>}{<text>}
(no need that the integers are consecutive or start from 0 like for\ifcase
); spaces are ignored between pairs; - (optional) text to be used after a successful match;
- text to be used for “no match”.