Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rewrite this code to improve its clarity?

Tags:

php

Could you write this 'cleaner' ? Just a simple question from a beginner:)

if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);

}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);

}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';

}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);

}else{
$act = "";
}
like image 463
eric Avatar asked Dec 28 '22 21:12

eric


2 Answers

I would do it like this:

$tid = isset( $_GET['tid'] ) ? trim( $_GET['tid'] ) : '';
$fid = isset( $_GET['fid'] ) ? trim( $_GET['fid'] ) : '';
$mid = isset( $_GET['mid'] ) ? trim( $_GET['mid'] ) : '';
$act = isset( $_GET['act'] ) ? trim( $_GET['act'] ) : '';

if ( empty( $act ) ) // act not set, construct the act from the other GET vars
{
    if ( !empty( $tid ) )
        $act = 'tid';
    else if ( !empty( $fid ) )
        $act = 'fid';
    else if ( !empty( $mid ) )
        $act = 'mid';
}

edit: Of course you could make this even shorter, but the question was how it could be written to “improve its clarity”. And I understand clarity as something that makes it more easy to understand, what happens in a part of code. And I think the actual logic behind the original code gets quite clear with my solution.

like image 104
poke Avatar answered Jan 09 '23 07:01

poke


I see nothing bad in your code apart from lack of indentation:

if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
    $act = 'tid';
    $tid = trim($_GET['tid']);

}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
    $act = 'fid';
    $fid = trim($_GET['fid']);

}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
    $act = 'mid';

}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
    $act = trim($_GET['act']);

}else{
    $act = "";
}

Although perhaps you could benefit from a function like this

function get_non_empty($field){
    return isset($_GET[$field]) && trim($_GET[$field])!='' ? $_GET[$field] : NULL;
}
like image 33
Álvaro González Avatar answered Jan 09 '23 07:01

Álvaro González