---
title: Avoid nested ternary expressions
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid nested ternary expressions
---

# Avoid nested ternary expressions

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `php-best-practices/no-nested-ternary`

**Language:** PHP

**Severity:** Notice

**Category:** Code Style

## Description{% #description %}

This rule is essential for maintaining clean, readable, and understandable code. Ternary expressions, while concise, can become complicated and hard to read when nested. This can lead to potential bugs and difficulties in debugging, especially in complex applications.

The importance of this rule lies in its contribution to code clarity and maintainability. Being able to understand what a piece of code does at a glance is vital for efficient development and for ensuring the code's correctness. Nested ternary expressions often require more cognitive effort to understand, compared to their equivalent structured control flow statements, such as `if-else` blocks.

To adhere to this rule, avoid using more than one ternary expression within a single statement. Instead, use structured control flow statements, such as `if-else` blocks. These are more verbose, but they are also more readable and easier to understand. For instance, instead of writing `$var = $a ? "a" : $b ? "b" : $c ? "c" : "d";`, you can write a series of `if-else` statements, as demonstrated in the compliant code sample.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```php
<?php
class Test {
    public function routine($a, $b, $c) {
        $var = $a ? "a" : $b ? "b" : $c ? "c" : "d";
    }
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```php
<?php
class Test {
    public function routine($a, $b, $c) {
        if ($a) {
            $var = "a";
        } else if ($b) {
            $var = "b";
        } else if ($c) {
            $var = "c";
        } else {
            $var = "d";
        }
    }
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 