如果函数内部有一个循环,如何创建和调用它


How to make and call a function if it has a loop inside of it?

我有一个 for 循环,显示数组内的所有图像。我怎样才能把它放在一个函数中,所以当我需要它时,我可以调用它,它会显示所有的图片?

$countArray = count($fil[0]);
function displayAllImages(){
for ($x=0; $x<$countArray; $x++){
    echo '<img src="photos/'.$fil[0][$x].'" /><br />';
}
}
displayAllImages(); //nothing shows up

由于您在函数外部声明了$fil和$countArray,因此无法访问它们,因此您应该将数组作为函数参数传递

function displayAllImages($images){
  $counter = count($images[0]);
  for ($x=0; $x < $counter; $x++){
      echo '<img src="photos/'.$images[0][$x].'" /><br />';
  }
}
displayAllImages($countArray, $fil); //now it will show up
执行

此类操作的最佳方法可能是使用 foreach 循环执行以下操作:

function displayAllImages($imagesSources){
  foreach($imagesSources as $value){
    echo '<img src="photos/'.$value.'" /><br />';
  }
}
$images = array("image1.png", "image2.png", "image3.png");
displayAllImages($images);
$images = array("0" => array("image1.png", "image2.png", "image3.png"));
//in this case you can pass directly $images[0] to the function as pointed in the comments
displayAllImages($images[0]);

正如评论中所指出的,请在此处查看PHP变量范围

原因是

,您在函数中使用了未声明的变量激活error_reporting,PHP 应该注意,$countArray没有声明。

2种可能性:

为函数提供数组作为参数:

// $fil[0] is an array
function displayAllImages($a)
{
    if(is_array($a)) foreach($a as $i => $v)
    {
        echo '<img src="photos/'.$v.'" /><br />';
    }
}
displayAllImages($fil[0]);

或者你在函数内部告诉 PHP,你想在函数外部使用变量:

// $fil[0] is an array
function displayAllImages()
{
    global $fil;
    if(is_array($fil[0])) foreach($fil[0] as $i => $v)
    {
        echo '<img src="photos/'.$v.'" /><br />';
    }
}
displayAllImages();

请看 http://php.net/manual/en/language.variables.scope.php