Last active
March 26, 2025 15:05
-
-
Save twysto/be2975c525c003a8d7f1f87373c3222b to your computer and use it in GitHub Desktop.
PHP | Flip an integer or a boolean to its opposite value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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