WHICHC or WHICHN

Earlier, we said the INDEX function searches for the first occurrence of the character string as a substring. The WHICHC and WHICHN functions search across a list of arguments and return the index of the first one that matches a given reference value. The reference value can only be specified as the first argument. There is no limit on the additional number of arguments that can be specified.

While WHICHC only works with character values and WHICHN only works with numeric values, both of them output a numeric value. If the first argument matches, it returns a value of 1; if the second argument matches, it returns a value of 2, and so on.

Let's understand the difference by looking at an example:

Data _NULL_;
Char = WhichC ("FromA", "FromB", "FromC", "FromA");
Char = WhichC ("FromA", "FromB", "FromC", "FromA");
Num = WhichN (100/25, 34, 4, 40, 10);
Zero = WhichC ("FromA", "FromB", "FromC", "From A");
Put Char= / Num= / Zero=;
Run;

This will result in the following message written to LOG:

 Char=3
Num=2
Zero=0
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.01 seconds

In the case of the CHAR variable, the first argument matches the fourth argument. As the search starts from the second argument, the value that's returned is 3. The first argument is the reference value and hence the counting of the value that's returned starts only from the second argument. The NUM variable returns a value 2 as 100/25 resolves to 4 and matches the third argument. In the case of ZERO, there is no match to the reference value as the fourth argument looks similar but has a minor difference in terms of the reference value.

Up until now, we have seen the use of the PUT statement, where we wrote multiple statements to ensure that the required values are written to LOG. However, in the preceding example, a single statement is showcased that can write multiple variable values to LOG.