4

I am trying to use \if within a tabularx environment. This works:

\documentclass{scrlttr2}

\usepackage{tabularx}

\begin{document}
    \newcounter{x} 
    \setcounter{x}{0}

    \begin{tabularx}{\linewidth}{c|l}
        \stepcounter{x}
            \ifnum\value{x}=20
            it is 20
            \else
            it is not
            \fi
            \\
    \end{tabularx} 

\end{document}

But of course has no columns. When I try to add them like this:

\documentclass{scrlttr2}

\usepackage{tabularx}

\begin{document}
    \newcounter{x} 
    \setcounter{x}{0}

    \begin{tabularx}{\linewidth}{c|l}
        \stepcounter{x}
            \ifnum\value{x}=20
            it is & 20
            \else
            it is & not
            \fi
            \\
    \end{tabularx} 

\end{document}

I get this error:

Incomplete \ifnum; all text was ignored after line 18. \end{tabularx}
Jagath
  • 4,287
Nathan
  • 461
  • Why can't you use this it is & \ifnum\value{x}=20\relax 20\else not\fi\\? – Jagath Jun 27 '16 at 15:21
  • @JagathAR well, my actual table has much more columns and the code gets ugly when I have to put the if into every cell. – Nathan Jun 27 '16 at 15:23
  • 1
    You could have a macro \TestX{20}{20}{not}. Where \def\TestX#1#2#3{\ifnum\value{x}=#1\relax #2\else #3\fi}. – Jagath Jun 27 '16 at 15:24

2 Answers2

3

If you must walk on a tightrope then:

enter image description here

\documentclass{scrlttr2}

\usepackage{tabularx}

\begin{document}
    \newcounter{x} 
    \setcounter{x}{0}
   \newcommand\zz[1]{#1}

\centering

    \begin{tabularx}{\linewidth}{c|X}
        \stepcounter{x}
            \ifnum\value{x}=20
            \zz{it is & 20}
            \else
            \zz{it is & not}
            \fi
            \\
    \end{tabularx} 

    \setcounter{x}{19}
    \begin{tabularx}{\linewidth}{c|X}
        \stepcounter{x}
            \ifnum\value{x}=20
            \zz{it is & 20}
            \else
            \zz{it is & not}
            \fi
            \\
    \end{tabularx} 

\end{document}
David Carlisle
  • 757,742
2

A conditional cannot straddle two cells. However you can use \ifthenelse:

\documentclass{article}

\usepackage{tabularx}
\usepackage{xifthen}

\begin{document}

\newcounter{x}
%\setcounter{x}{0}

\begin{tabular}{c|l}
\stepcounter{x}%
\ifthenelse{\value{x}=20}{it is & 20}{it is & not}\\
\setcounter{x}{20}%
\ifthenelse{\value{x}=20}{it is & 20}{it is & not}\\
\end{tabular}

\setcounter{x}{0}

\begin{tabularx}{.5\textwidth}{c|X}
\stepcounter{x}%
\ifthenelse{\value{x}=20}{it is & 20}{it is & not}\\
\setcounter{x}{20}%
\ifthenelse{\value{x}=20}{it is & 20}{it is & not}\\
\end{tabularx}

\end{document}

enter image description here

egreg
  • 1,121,712