如何合并PHP验证$_GET['st']的两行代码?求更优简化方案
Got it, let's work through this. Your goal is to guarantee that the st GET parameter (and thus $status) is always either ac or ar—even if someone messes with the URL parameters. You want to combine those two conditional checks into one line, or just simplify the overall logic entirely. Here's how to do both:
Option 1: Combine the Two Checks into a Single Condition
You can merge the "parameter not set" and "parameter is invalid" checks into one if statement using logical OR (||). This makes the code shorter and easier to read:
if (!isset($_GET['st']) || !in_array($_GET['st'], ['ac', 'ar'], true)) { header('Location: notes.php?st=ac'); exit; // Critical: Stop execution after redirect to prevent unwanted code runs } $status = $_GET['st'];
Why this works:
- The first part (
!isset($_GET['st'])) catches cases where thestparameter is missing entirely. - The second part (
!in_array(...)) checks if the provided value isn't in our allowed list (ac/ar). Thetrueflag enforces strict type matching (so no accidental matches with non-string values). - We add
exitright after the header redirect because PHP will keep executing code unless we tell it to stop—this prevents any unintended behavior after the redirect.
Option 2: Even More Concise (PHP 7+)
If you're using PHP 7 or newer, you can use the null coalescing operator (??) to handle the "parameter not set" case in one line, then validate:
$status = $_GET['st'] ?? 'ac'; // Default to 'ac' if st is missing if (!in_array($status, ['ac', 'ar'], true)) { header('Location: notes.php?st=ac'); exit; }
Or if you want to condense it even further (though readability should be a priority):
$allowed = ['ac', 'ar']; $status = in_array($_GET['st'] ?? '', $allowed, true) ? $_GET['st'] : 'ac'; // If you still need to redirect instead of just setting the value, keep the header/exit check
A Quick Note on Your Original Code
Your original code had a small edge case: if $_GET['st'] wasn't set, you redirected, but you never defined $status in that scenario before the second if check. That would throw an undefined variable warning. The merged/simplified versions above avoid that entirely.
内容的提问来源于stack exchange,提问作者qadenza

