I am having the darndest time figuring out how to use a foreach
inside a function
.I have rewritten my code down to the simplest form and still cannot get it to run. This is the simple version of what I am trying to do:
$arr = array("first","second","third");
function myFunction(){
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction();
I know the solution must be one of those "doh" moments but I must risk embarrassment 'cause I can't get it...
In PHP global variables need to be said inside the function. You simply need to say you using a global variable otherwise PHP won't know. So you just need to add global $arr;
like so:
$arr = array("first","second","third");
function myFunction(){
global $arr; // <-- This states we are using the $arr defined globally.
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction();
$arr = array("first","second","third");
function myFunction($target){
foreach($target as $val){
echo $val.' | ';
}
}
myFunction($arr);//$arr will send to function for process
Have a try!
You can also pass array to the function.
$arr = array("first","second","third");
function myFunction($arr){
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction($arr);