Skip to content
Advertisement

Short IF and Long IF Variable Assignment Method in PHP

I have 2 codes that do the same task. 2.In the long code $sort = 'newest'; I’m throwing the variable. But in the 1st shortcode I don’t know how to assign it.

*The code to be edited is the 1st Code. (Short Code)

Short IF PHP Code

$sql_code_orderby = ( $sort == 'oldest' ? "ORDER BY Q.created ASC" : ($sort == 'votes' || ($sort == '' && $filter == 'noanswers')) ? "ORDER BY Q.vote_count DESC" : ($sort == 'viewed' ? "ORDER BY Q.viewed DESC" : "ORDER BY Q.created DESC" ) );

Long IF PHP Code

if( $sort == 'oldest' ){
    $sql_code_orderby = "ORDER BY Q.created ASC";
} else if( $sort == 'votes' || ($sort == '' && $filter == 'noanswers')  ){
    $sql_code_orderby = "ORDER BY Q.vote_count DESC";
} else if( $sort == 'viewed' ){
    $sql_code_orderby = "ORDER BY Q.viewed DESC";
} else {
    $sort = 'newest';
    $sql_code_orderby = "ORDER BY Q.created DESC";
}

My fault trial result:

$sql_code_orderby = ( $sort == 'oldest' ? "ORDER BY Q.created ASC" : ($sort == 'votes' || ($sort == '' && $filter == 'noanswers')) ? "ORDER BY Q.vote_count DESC" : ($sort == 'viewed' ? "ORDER BY Q.viewed DESC" : "ORDER BY Q.created DESC" .  ($sort = 'newest') ) );

Advertisement

Answer

Using nested ternary expressions like the “short code” are generally considered bad practice as they are difficult to read, understand, and maintain. In a team environment, I would expect any code that uses them to be rejected in code review.

In a case like this, I’d probably use a switch statement something like the below:

$direction = 'DESC';

switch (true) {
    case $sort === 'oldest':
        $column = "created";
        $direction = 'ASC';
        break;
    case $sort === 'votes':
    case $sort === '' && $filter === 'noanswers':
        $column = "vote_count";
        break;
    case $sort === 'viewed':
        $column = "viewed";
        break;
    default:
        $column = "created";
        break;
}

$sql_code_orderby = "ORDER BY Q.$column $direction";
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement