Skip to content

Instantly share code, notes, and snippets.

@remino
Last active June 26, 2024 04:52
Show Gist options
  • Save remino/421f306478d8c4ef00cd1c928cb99c2e to your computer and use it in GitHub Desktop.
Save remino/421f306478d8c4ef00cd1c928cb99c2e to your computer and use it in GitHub Desktop.
Nested ternary examples in JavaScript, Python, PHP

ternary-example

Example of nested ternary not acting the same in JavaScript and PHP.

Furthermore, PHP 8.0 now throws a fatal error when nested ternaries are used without parentheses.

Conclusion: just don't use nested ternaries.

Usage

# Run the JavaScript example
./ternary.js

# Run the Python example
./ternary.py

# Run the PHP examples using Docker
docker-compose up --build

Expected output

JavaScript
two

Python
two

ternary-php7-1  | PHP 7.4.33
ternary-php7-1  | three
ternary-php7-1 exited with code 0

ternary-php8-1  |
ternary-php8-1  | Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in /usr/src/myapp/ternary.php on line 9
ternary-php8-1 exited with code 255
version: '3.8'
services:
ternary-php7:
build:
context: .
dockerfile: Dockerfile.php7
volumes:
- ./ternary.php:/usr/src/myapp/ternary.php
ternary-php8:
build:
context: .
dockerfile: Dockerfile.php8
volumes:
- ./ternary.php:/usr/src/myapp/ternary.php
FROM php:7.4-cli
COPY ternary.php /usr/src/myapp/ternary.php
WORKDIR /usr/src/myapp
CMD [ "php", "./ternary.php" ]
FROM php:8.3-cli
COPY ternary.php /usr/src/myapp/ternary.php
WORKDIR /usr/src/myapp
CMD [ "php", "./ternary.php" ]
#!/usr/bin/env node
console.log('JavaScript')
const a = 2;
console.log(
a === 1 ? 'one'
: a === 2 ? 'two'
: a === 3 ? 'three'
: 'other'
)
#!/usr/bin/env php
<?php
echo "PHP " . PHP_VERSION . "\n";
$a = 2;
print(
$a === 1 ? 'one'
: $a === 2 ? 'two'
: $a === 3 ? 'three'
: 'other'
);
#!/usr/bin/env python3
print('Python')
a = 2
print(
'one' if a == 1
else 'two' if a == 2
else 'three' if a == 3
else 'other'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment