开发者

How can I tidy multiple if condition for readability?

开发者 https://www.devze.com 2023-03-25 06:33 出处:网络
How can I tidy multiple if condition for readability? For instance, if( $key != \'pg_id\' && $key != \'pg_tag\' && $key != \'pg_user\')

How can I tidy multiple if condition for readability?

For instance,

if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user'  )

This confuses me when the items in that condition grow longer.

It was used in this kind of situation below - foreach(),

$editable_fields = array(
    'pg_id',
    'pg_开发者_运维知识库url',
    'pg_title',
    'pg_subtitle',
    'pg_description',
    'pg_introduction',
    'pg_content_1',
    'pg_content_2',
    'pg_content_3',
    'pg_content_4',
    'pg_backdate',
    'pg_highlight',
    'pg_hide',
    'pg_cat_id',
    'ps_cat_id',
    'parent_id',
    'tmp_id',
    'usr_id'
);

$sql_pattern = array();

foreach( $editable_fields as $key )
{
    if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user'  ) $sql_pattern[] = "$key = ?";
}

I was thinking using switch but I think I was wrong!


You could use in_array:

if (!in_array($key, array('pg_id', 'pg_tag', 'pg_user'))


One possible solution could be to put each condition on it's own line:

foreach( $editable_fields as $key )
{
    if( $key != 'pg_id' && 
        $key != 'pg_tag' && 
        $key != 'pg_user'  )
    { 
        $sql_pattern[] = "$key = ?";
    }
}

I find this clarifies these types of compound conditions for me.


So, use line-breaks:

if( $key != 'pg_id' &&
    $key != 'pg_tag' &&
    $key != 'pg_user'
 ){
    $sql_pattern[] = "$key = ?";
}

Makes it more readable.

A switch-statement is meant to test only for one condition. Like if you would check for a number.

$number = 12;
switch($number){
  case 1:
    // Do stuff...
  case [...]
}


You can either spread it out:

if(
    $key != 'pg_id' && 
    $key != 'pg_tag' && 
    $key != 'pg_user'
) {
    /* code here */
    $sql_pattern[] = "$key = ?"
}

... or use a switch statement

switch ($key) {
    default:
        /* code here */
        $sql_pattern[] = "$key = ?"
        break;
    case 'pg_id':
    case 'pg_tag':
    case 'pg_user':
        break;
}


Refactor into a function with a name that describes its purpose:

function KeyIsNotMatch($key) {
    if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user'  )
        return true;
    else
        return false;
}

foreach( $editable_fields as $key )
{
    if (KeyIsNotMatch($key)) $sql_pattern[] = "$key = ?";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消