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
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
The best way to do such a thing would probably be the following using the foreach loop:
and as pointed in the comments have a look at php variable scope HERE
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:
or you tell PHP inside the function, that you want to use a variable outside the function:
please look at http://php.net/manual/en/language.variables.scope.php