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

560

I have a for loop that displays all of the images inside of an array. How can I put that inside of a function, so when I need it I can call it and it will show all of the pictures?

$countArray = count($fil[0]);

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

Answer

Solution:

Since you declared $fil and $countArray outside the function, you have no access to them, so you should pass the array as a function argument

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

The best way to do such a thing would probably be the following using the foreach loop:

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]);

and as pointed in the comments have a look at php variable scope HERE

999

Answer

Solution:

the reason is, that you use a variabe inside a function, that is not declared activate error_reporting, and PHP should note, that $countArray isn't declared.

2 possibilities:

giving the functino the Array as a Parameter:

// $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]);

or you tell PHP inside the function, that you want to use a variable outside the function:

// $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();

please look at http://php.net/manual/en/language.variables.scope.php

People are also looking for solutions to the problem: php - how to check session flashdata in helper in CI

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.