Switch
The switch statement in PHP lets you handle multiple possible values for a single variable without piling up a ton of if and elseif statements. You give it an expression, and PHP compares that value against a list of “cases.” When it finds a match, it runs that block of code.
Here’s the basic idea:
switch ($status) {
case 'active':
echo 'The membership is active.';
break;
case 'expired':
echo 'The membership has expired.';
break;
case 'pending':
echo 'The membership is pending approval.';
break;
default:
echo 'Unknown membership status.';
}
In this example, $status could represent a user’s MemberPress subscription state. PHP checks each case in order until one matches, then runs that block. The break statement tells PHP to stop checking further cases once it finds a match — otherwise, it’ll “fall through” and continue running the next case, which usually causes unintended results.
For instance, if you forget break after 'active', PHP would also execute 'expired' right after it, even if $status was only 'active'.
The default case works like a fallback — it runs only if none of the other cases match. You can technically place it anywhere in the switch, but most developers keep it at the end for readability.
Finally, you can group several cases together when they share the same outcome. For example:
switch ($day) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
echo 'Regular support hours.';
break;
case 'Saturday':
case 'Sunday':
echo 'Weekend mode: limited support.';
break;
default:
echo 'Invalid day.';
}
This keeps your code clean and avoids repeating the same echo line for multiple cases.