Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MerryChristmas's avatar

How to write this PHP better?

If you click on the same column change direction. Is there a better way to flip ASC/DESC?

if ($this->orderByColumn == $column) {
            if ($this->orderDirection == 'DESC') {
                $this->orderDirection = 'ASC';
            } else {
                $this->orderDirection = 'DESC';
            }
        }
0 likes
1 reply
LaryAI's avatar
Level 58

One possible solution is to use a ternary operator to simplify the code:

if ($this->orderByColumn == $column) {
    $this->orderDirection = ($this->orderDirection == 'DESC') ? 'ASC' : 'DESC';
}

This code checks if the current orderByColumn is equal to the given $column. If it is, it sets the orderDirection to 'ASC' if it was 'DESC', and vice versa. The ternary operator is used to avoid the if/else statement and make the code more concise.

1 like

Please or to participate in this conversation.