Skip to content
Advertisement

PHP Any better way to write this if + ternary function?

Basically it just switches between the two values. If I input X I get 6, if I input 6 I get X. If I input anything else the value comes through unchanged.

function change($val) {
  if ($val == "X" || $val == 6) { $val = $val=="X" ? 6 : "X"; } else
  if ($val == "J" || $val == 3) { $val = $val=="J" ?  3 : "J"; }
  return $val;
}

This is a simplified version of the function I’m actually using so no need to ask why I need it. I tried it as and array but it doesn’t work since I will input other numbers which need to output without changing. It needs to input all numbers and letters but only change ones in the function, others should go through untouched.

Expected output.

change(6)
X
change(8)
8
change(X)
6
change(L)
L
change(3)
J

I’m basically looking for a simpler way to write this function if there is one. It just looks ugly to me as it is but it’s fine if there is no better way.

Editing to add an additional condition since I didn’t realise that the code might be very different for one, or more than one condition. The actual code has five conditions you see.

Advertisement

Answer

You could use this solution if you’re using PHP >7.0:

function change($val)
{
    return [6 => 'X', 'X' => 6][$val] ?? $val;
}

For lower versions it could be like:

function change($val)
{
    $changes = [6 => 'X', 'X' => 6];

    return isset($changes[$val]) ? $changes[$val] : $val;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement