Reputation: 559
I have a fairly large if/elseif/else conditional and I'm wondering if this could possibly be the best way of doing this, or if there's a better way?
if (($site == '1') && ($theAction == 'subscribe')) {
$url = "https://test1.com/?na=ajaxsub";
} elseif (($site == '2') && ($theAction == 'subscribe')) {
$url = "https://test2.com/?na=ajaxsub";
} elseif (($site == '3') && ($theAction == 'subscribe')) {
$url = "https://test3.com/?na=ajaxsub";
} elseif (($site == '4') && ($theAction == 'subscribe')) {
$url = "https://test4.com/?na=ajaxsub";
} elseif (($theAction == 'unsubscribe') && ($site == '1' | '2' | '3' | '4')) {
$url = "https://test5.com/unsubscribe.php";
} else {
return;
}
Upvotes: 0
Views: 54
Reputation: 42354
For starters, it seems as though you want to redirect to the same page whenever a user is trying to unsubscribe, regardless of what $site
is, so you can take this part completely out of the equation.
From here, I would recommend making an associative array that maps each $site
index to their corresponding site. You can then simply set $url
based on the index of this new assictaive array as follows:
$site = 1; // Set the site as an integer
$theAction = 'subscribe'; // As long as it is not 'unsubscribe' the `else` will trigger
$mappings = array("1"=>"https://test1.com/?na=ajaxsub",
"2"=>"https://test2.com/?na=ajaxsub",
"3"=>"https://test3.com/?na=ajaxsub",
"4"=>"https://test4.com/?na=ajaxsub");
if ($theAction == 'unsubscribe') {
$url = "https://test5.com/unsubscribe.php";
}
else {
$url = $mappings[$site];
}
echo $url; // https://test1.com/?na=ajaxsub
This can be seen working here.
And you can even shrink down the conditional using a ternary, if you so desire:
$theAction == 'unsubscribe' ? $url = "https://test5.com/unsubscribe.php" : $url = $mappings[$site];
Which can be seen working here.
Upvotes: 1