0

I currently have 2 functions; i need to read one array that's inside one of the functions from the inside of the other function:

function a(){

 foreach ($options as $option){ // $options is a variable from function b()
  // here goes a really long loop
 }

}

function b(){

 $options[] = array(
   'key1' => 1,
   'key2' => 2,
   'key3' => 3,
  );

 function a(); // run function here?
}

My php file is gonna have multiple copies of what we call "function b()". And inside each function b(), i wanna run function a(), but use the array content that's inside the function b().

function a() contains a loop that's always the same but really long, i just want to keep my code as short as possible instead of copying function a() inside each function b().

This is probably really easy but i've been struggling with this issue for a long time now!

2 Answers 2

3

Just return the array from b() and then pass it as a parameter to a()

function a($options){
    foreach ($options as $option){ 
      // here goes a really long loop
    }
}

function b(){
   $options = array(
       'key1' => 1,
       'key2' => 2,
       'key3' => 3,
   );
   a($options);
}
Sign up to request clarification or add additional context in comments.

2 Comments

forgot to mention that i must run function a() inside function b(). function b() is in my scenario a tab on a webpage. Got another solution?
Updated my answer accordingly
1

Could you not simply pass it as a function argument?

function a($options){
    foreach ($options as $option){ // $options is a variable from function b()
        // here goes a really long loop
    }
}

function b(){
    a(array(
        'key1' => 1,
        'key2' => 2,
        'key3' => 3,
    ));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.