PHP处理可能未设置的变量的最佳方法是什么?

时间:2010-08-14 03:00:35

标签: php

我有一个foreach循环,它会遍历一个数组,但是这个数组可能不存在,具体取决于这个特定应用程序的逻辑。

我的问题与我猜最佳做法有关,例如,可以这样做:

if (isset($array))
{

    foreach($array as $something)
    {
        //do something
    }
}

对我来说这似乎很麻烦,但在这种情况下,如果我不这样做,它就会在foreach上出错。我应该传递一个空数组?我没有发布特定代码,因为它是关于处理可能设置或未设置的变量的一般问题。

5 个答案:

答案 0 :(得分:8)

请注意:这是'最安全'的方式。

if (isset($array) && is_array($array)) {
    foreach ($array as $item) {
        // ...
    }
}

答案 1 :(得分:1)

尝试:

 if(!empty($array))
 {
     foreach($array as $row)
     {
         // do something
     }
 }

答案 2 :(得分:0)

这根本不是一团糟。事实上,这是最好的做法。如果我不得不指出任何杂乱的东西,那就是使用Allman支撑式,但这是个人喜好。 (我是1TBS的那种人);)

我通常会在所有类方法中执行此操作:

public function do_stuff ($param = NULL) {
    if (!empty($param)) {
        // do stuff
    }
}

关于empty()的单词。有些情况下isset是可取的,但是如果没有设置变量则为空,或者如果它包含空字符串或数字0之类的“空”值。

答案 3 :(得分:0)

如果你将一个空数组传递给foreach,那么它很好,但如果你传递一个未初始化的数组变量,那么它将产生错误。

当数组为空或甚至未初始化时,它将起作用。

if( !empty($array) && is_array($array) ) {
   foreach(...)
}

答案 4 :(得分:-1)

我想说最好有一个'boolean'其他值设置为0(PHP为false)以启动,并且任何时候某个函数添加到此数组,添加+1到布尔值,所以你'我有一个明确的方法来知道你是否应该搞乱阵列?

这是我在面向对象语言中采用的方法,在PHP中它可能会更加混乱,但我仍然觉得最好有一个有意识的变量保持跟踪,而不是尝试分析数组本身。理想情况下,如果此变量始终为数组,请将第一个值设置为0,并将其用作标志:

 <?PHP
 //somewhere in initialization
 $myArray[0] = 0;
 ...
 //somewhere inside an if statement that fills up the array
 $myArray[0]++;
 $myArray[1] = someValue;

 //somewhere later in the game:
 if($myArray[0] > 0){          //check if this array should be processed or not
      foreach($myArray as $row){     //start up the for loop
           if(! $skippedFirstRow){   //$skippedFirstRow will be false the first try
                $skippedFirstRow++;  //now $skippedFirstRow will be true
                continue;            //this will skip to the next iteration of the loop
           }
           //process remaining rows - nothing will happen here for that first placeholder row
      }
 }
 ?>