1

I need to call functions as per foreach key value matches. Like asso1 key will call asso1() function and asso2 key will call asso2() function. I mean function name is dynamic. Array key value will be the functions name which need to be called. How can I achieve this?

function asso1() {
  echo "output form asso1";
}
function asso2() {
  echo "output form asso2";
}
function asso3() {
  echo "output form asso3";
}
$asso = array("asso1"=>"1", "asso2"=>"2", "asso3"=>"3");

foreach ($asso as $key => $_asso) {
  print_r($key);  //this will be name of function which need to be called.
  // print_r($_asso);
}

2 Answers 2

1

call_user_func is your savior. you can get more information from here: http://php.net/manual/en/function.call-user-func.php

for example:

foreach ($asso as $key => $_asso) {
    call_user_func($key);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the call_user_func() function in this way:

foreach ($asso as $key => $_asso) {
    call_user_func($key);  
}

You can also use Variable functions

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.