在创建新变量时检查变量是否为isset

时间:2017-07-19 13:46:26

标签: php if-statement concatenation isset

我正在尝试创建一个动态描述,其中测试更改了产品特性,如果产品具有该功能/特性,我创建了所有单独的文本块,现在我正在编译所有文本但是为了最终描述,我需要在创建变量时检查每个变量是否都设置。

请看下面我正在尝试的内容:

$description = isset($desc1)? echo $desc1 :'' . isset($desc2)? echo $desc2 :';

我需要检查大约20个不同的变量,如果它们是isset,那么单独的if语句不是一个选项。我做了很多研究,找不到解决方案

感谢您的帮助

编辑:

如何设置变量:

$desc1 = "Released " . $model['month'] . " " . $model['year'] . "," . " ". "the" . " " . $brand['brand'] . " " . $model['model'] . " " . "is an";
if ($model['interchangeable'] == 1) { 
    $desc2 = "interchangeable lens" . " " . substr($category_name['category'], 0, -1) . " "; 
} elseif ($model['interchangeable'] == 0) { 
    $desc2 = "fixed lens" . " " . substr($category_name['category'], 0, -1) . " "; 
}
$desc3 = "that scores";
if ($score[0] >= 70) { $desc4 = "highly"; } elseif ($score[0] >= 40) { $desc4 = "moderately"; } elseif ($score[0] < 40) { $desc4 = "poorly"; } 
$desc5 = "at" . " " . $score[0] . "/100" . " " . "in comparison with other cameras."; 
$desc6= "Some stand out features is the" . " " . $model['mp'] . " " .  "sensor"; 


if (strpos($res, "-") !== FALSE) { } else { 
    $desc7 = "capable of recording at" . " " . $model['res'] . " " . "resolution" . " "; 
}
$desc8 = "also";
if ($model['interchangeable'] == 1) { 

    if (strpos($model['focus_points'], "-") !== FALSE) { } else { 
        $desc9x1 = "-" . " " . $model['focus_points'] . " " . "Points" . " ";
    }
    if (strpos($model['frame_rate'], "-") !== FALSE) { } else { 
        $desc9x2 = "-" . " " . $model['frame_rate'] . " " . "Burst Rate" . " ";
    }
    if (strpos($model['sensor_size'], "-") !== FALSE) { } else { 
        $desc9x3 = "-" . " " . $model['sensor_size'] . " " . "Sensor" . " ";
    }
    if (strpos($model['viewfinder'], "None") !== FALSE) { } else { 
        $desc9x4 = "-" . " " . $model['viewfinder'] . " " . "Viewfinder" . " ";
    }


} elseif ($model['interchangeable'] == 0) { 

    if (strpos($model['zoom'], "-") !== FALSE) { } else { 
        $desc9x1 = "-" . " " . $model['zoom'] . " " . "Zoom" . " ";
    }
    if (strpos($model['macro_focus'], "-") !== FALSE) { } else { 
        $desc9x2 = "-" . " " . $model['macro_focus'] . " " . "Macro Focus" . " ";
    }
    if (strpos($model['wide_angle'], "-") !== FALSE) { } else { 
        $desc9x3 = "-" . " " . $model['wide_angle'] . " " . "wide-angle lens" . " ";
    }


}
if (strpos($model['screen_size'], "-") !== FALSE) { } else { 

    $desc9 = "and a" . " " . $model['screen_size'] . " " . "inch screen.";

} 

1 个答案:

答案 0 :(得分:0)

当您使用这样的三元运算符时,您不应该内联回显,而是打印结果变量$description。然后,您需要使用括号对条件进行分组,否则您可能无法得到预期的结果。

echo $description = (isset($desc1) ? $desc1 : '') . (isset($desc2) ? $desc2 : '');

或者,如果在将字符串连接在一起时使用逗号而不是句点,则可以避免对它们进行分组。

echo $description = isset($desc1) ? $desc1 : '', isset($desc2) ? $desc2 : '';

如果您有超过20个变量,将它们全部存储在数组中会更容易,并根据需要过滤它们,然后使用该数组打印您需要的内容。如果您展示了一些扩展的代码结构,我可以编辑我的答案以显示解决方案。