如何根据我在php中的条件使用switch case

时间:2015-03-10 04:34:39

标签: php codeigniter laravel

 if($this->input->get('i1')!='' && $this->input->get('i2')=='' && $this->input->get('i3')=='' && $this->input->get('i4')=='')
            {
                echo 'i1';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')=='' && $this->input->get('i4')=='')
            {
                echo 'i1  i2 ';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')!='' && $this->input->get('i4')=='')
            {
                echo 'i1 i2 i3';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')!='' && $this->input->get('i4')!='')
            {
                echo 'i1 i2 i3 i4';
            }

如何在开关案例中使用此条件......任何人都可以帮助我。

4 个答案:

答案 0 :(得分:0)

一种可能的解决方案是生成类似位掩码。

定义只是为了使代码更具可读性。

// create costants to make the code more readable           
define('I1', '1000'); 
define('I1_I2', '1100'); 
define('I1_I2_I3', '1110'); 
define('I1_I2_I3_I4', '1111'); 

// controll you input and cast in iteger
// true  -> 1
// false -> 0
for ($i = 1; $i < 5; $i++) {
    $var  = 'i' . $i;
    $$var =  $this->input->get($var)
    $$var = (int) !empty($$var);
}

// generate a mask
// eg : 1000
$mask = $i1.$i2.$i3.$i4;

switch ($mask) {
    case I1:
        echo 'i1';
        break;
    case I1_I2:
        echo 'i1 i2';
        break;
    case I1_I2_I3:
        echo 'i1 i2 i3';
        break;
    case I1_I2_I3_I4:
        echo 'i1 i2 i3';
        break;
}

答案 1 :(得分:0)

我知道这不是一个转换案例,但是既然你澄清了你想要简化的话,这是否适合你的需要?

for($x=1;$x<=4;$x++){
    if(!empty($this->input->get('i'.$x)) echo "i$x ";
}

答案 2 :(得分:0)

不是一个真正的答案,但是看起来也不那么冗长。

if($this->input->get('i1')!='')
{
    echo 'i1 ';
    if($this->input->get('i2')!='')
    {
        echo 'i2 ';
        if($this->input->get('i3')!='')
        {
            echo 'i3 ';
            if($this->input->get('i4')!='')
            {
                echo 'i4 ';
            } 
        } 
    } 
}

答案 3 :(得分:0)

我不认为开关盒在这里有助于简化。相反,我建议一个更动态的解决方案像这样:

$inputs = $this->input->only('i1', 'i2', 'i3', 'i4');
$notEmptyInputs = array_filter($inputs);
echo implode(' ', array_keys($notEmptyInputs));

如果您不希望输出i1 i4但仅i1,如果未设置2和3,请使用此选项:

$inputs = $this->input->only('i1', 'i2', 'i3', 'i4');
$notEmptyInputs = [];
foreach($inputs as $key => $value){
    if(empty($value)){
        break;
    }
    $notEmptyInputs[] = $key;
}
echo implode(' ', $notEmptyInputs);