Skip to content

Instantly share code, notes, and snippets.

@twysto
Last active March 26, 2025 15:05
Show Gist options
  • Save twysto/be2975c525c003a8d7f1f87373c3222b to your computer and use it in GitHub Desktop.
Save twysto/be2975c525c003a8d7f1f87373c3222b to your computer and use it in GitHub Desktop.
PHP | Flip an integer or a boolean to its opposite value
<?php
function flip(int|bool $val): int|bool
{
$output = $val ^ 1;
settype($output, gettype($val));
return $output;
}
// Usage:
echo flip(0) . PHP_EOL; // 1
echo flip(1) . PHP_EOL; // 0
echo (flip(true) ? 'true' : 'false') . PHP_EOL; // false
echo (flip(false) ? 'true' : 'false') . PHP_EOL; // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment