How to convert `if condition` to `switch` method

后端 未结 3 1574
孤街浪徒
孤街浪徒 2021-01-28 10:27

How can I write this if condition in switch method?

if( $k != \'pg_id\' && $k != \'pg_tag\' && $k != \'pg_user\' )
{
           


        
相关标签:
3条回答
  • 2021-01-28 11:06

    A switch condition is likely to be faster (jump table) and a bit easier to read. You can skip the break; if the result of the condition is the same and an improved syntax is to use curly braces inside each condition:

    switch ($k)
    {
     case 'pg_id':
     case 'pg_tag':
     case 'pg_user': {
     break;
     }
     default: {
       $result = $connection->run_query($sql,array(...));
     }
    }
    
    0 讨论(0)
  • 2021-01-28 11:07

    (Borrowing from a previous question which I believe spawned this one - A short-cut to update a table row in the database?)

    $editable_fields = array(
      'pg_url' ,
      'pg_title' ,
      ...
    );
    /* These are the fields we will use the values of to match the tuple in the db */
    $where_fields = array(
      'pg_id' ,
      'pg_tag' ,
      'pg_user' ,
      ...
    );
    
    $form_values = array();
    $sql_pattern = array();
    foreach( $editable_fields as $k ){
      if( $k != 'pg_id'
          && isset( $_POST[$k] ) ){
        $form_values[$k] = $_POST[$k];
        // NOTE: You could use a variant on your above code here, like so
        // $form_values[$k] = set_variable( $_POST , $k );
        $sql_pattern[] = "$k = ?";
      }
    }
    $where_values = array();
    $where_pattern = array();
    foreach( $where_fields as $k ){
      if( isset( $_POST[$k] ) ){
        $where_values[$k] = $_POST[$k];
        // NOTE: You could use a variant on your above code here, like so
        // $form_values[$k] = set_variable( $_POST , $k );
        $where_pattern[] = "$k = ?";
      }
    }
    
    $sql_pattern = 'UPDATE root_pages SET '.implode( ' , ' , $sql_pattern ).' WHERE '.implode( ' , ' , $where_pattern );
    
    # use the instantiated db connection object from the init.php, to process the query
    $result = $connection->run_query($sql_pattern,array_merge(
        $form_values ,
        $where_values
        ));
    
    0 讨论(0)
  • 2021-01-28 11:10

    Use break to prevent follow through to next case:

    switch($k)
    {
    case 'pg_id':
    case 'pg_tag':
    case 'pg_user':
      // any match triggers this block; break causes no-op
      break;
    default:
      $result = $connection->run_query($sql,array(...));
    }
    

    I'm not sure why you want to use a switch statement for this though.

    If it's for readability, you could try this instead:

    if($k != 'pg_id' &&
       $k != 'pg_tag' &&
       $k != 'pg_user')
    {
      $result = $connection->run_query($sql,array(...));
    }
    
    0 讨论(0)
提交回复
热议问题