使用foreach修复/改进if语句不为null

时间:2012-03-16 14:38:32

标签: php if-statement foreach null switch-statement

拥有此代码:

$main = !empty($searchResults['main']) ? $searchResults['main'] : null;
$second = !empty($searchResults['second']) ? $searchResults['second'] : null;
$third = !empty($searchResults['third']) ? $searchResults['third'] : null;

#if(($main) || ($second) || ($third))
if((($main) || ($second) || ($third)) !== NULL)
{
    foreach ((array)$searchResults as $key => $value)
    {
        switch ($key)
        {
            case "main":
            ....

如何修复/改进此代码?

通过修复我的意思是我需要一种方法来避免在空键上运行开关

2 个答案:

答案 0 :(得分:1)

foreach ($searchResults as $key => $value)
{
  if(empty($value)) continue;
  ...

答案 1 :(得分:0)

我个人会这样做

if(!empty($searchResults['main'])
{
    $main = $searchResults['main'];
    //do stuff
}

if(!empty($searchResults['second'])
{
    $second = $searchResults['second'];
    //do stuff
}  

...等。