Reputation: 12314
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.
Upvotes: 1
Views: 84
Reputation: 6379
switch/case seems to be the most readable option for me:
<?php
function change($input) {
switch($input) {
case 'X':
return 6;
case 6:
return 'X';
default:
return $input;
}
}
var_dump(change(6));
var_dump(change('X'));
var_dump(change('something_else'));
Output for 7.1.25 - 7.3.2
string(1) "X"
int(6)
string(14) "something_else"
If you don't like multiple return statements in a function you could aswell refactor it:
<?php
function change($input) {
$return = $input;
switch($input) {
case 'X':
$return = 6;
break;
case 6:
$return = 'X';
break;
}
return $return;
}
var_dump(change(6));
var_dump(change('X'));
var_dump(change('something_else'));
Upvotes: 1
Reputation: 2038
Use ternary operator:
// Return 6 if $val is 'X'
// Return 'X' if $val is 6
// Return same if $val is not 'X' and 6
function change($val) {
return (($val == "X") ? 6 : ($val == 6 ? 'X' : $val));
}
Adding a new (3rd) condition in it:
// Return 6 if $val is 'X'
// Return 'X' if $val is 6
// Return 3 if $val is 'J'
// Return 'J' if $val is 3
// Return same if $val is not 'X' and 6
function change($val) {
return ($val == "X") ? 6 :
($val == 6 ? 'X' :
($val == 'J') ? 3 :
($val == 3) ? 'J' :
$val
);
}
Upvotes: 1
Reputation: 119
function change($val) {
return $val == 6 ? "X" : ($val == "X" ? 6 : $val);
}
Upvotes: 0
Reputation: 24276
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;
}
Upvotes: 5
Reputation: 4766
Depending on the use-case you should be able to use str_replace().
$string = str_replace([6, 'X'], ['X', 6]);
Upvotes: 0