Reputation: 169
I got the following code and Is it possible to do the else condition as a ternary:
if (condition) {
//do something
} else {
if (isset($_POST['A'])) {
header("Location: /LocationA");
exit;
}
if (isset($_POST['B'])) {
header("Location: /LocationB");
exit;
}
}
I tried doing the following, but I'm not sure if I am right:
isset($_POST['A']) ? header("Location: /LocationA")
: header("Location: /LocationB}");
exit;
I only need to change the ELSE on the statement. So it's gonna be like :
if (condition) {
//do something
} else {
//ternary
}
Upvotes: 0
Views: 57
Reputation: 360
try it
isset($_POST['A'])
?
header("Location: /LocationA");
:
header("Location: /LocationB");
exit;
i think it works. :)
Upvotes: 0
Reputation: 72256
but I'm not sure if I am right
You are not right.
The ternary operator (?:
) is an operator. As the documentation says:
An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).
Please note the words "values" and "expression" in the sentence above.
The PHP function header()
doesn't return anything. The call header(...)
doesn't have a value, it has only side-effects (it modifies the status of the program).
You are trying to replace an if
statement with an operator. They are different things, have different purposes in the language and follow different rules. Changing one for another doesn't work.
The expression you posted:
isset($_POST['A']) ? header("Location: /LocationA")
: header("Location: /LocationB}");
doesn't have the same effect as the if
statement you are trying to replace.
There is an if (isset($_POST['B']))
in the original piece of code that is missing in the rewritten code.
Without caring about $_POST['B']
, you can write the code like this:
if (condition) {
//do something
} else {
header(isset($_POST['A'] ? 'Location: /LocationA' : 'Location: /LocationB');
exit();
}
Or, even shorter:
header('Location: ' . (isset($_POST['A']) ? '/LocationA' : '/LocationB'));
Upvotes: 5