Reputation: 25
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);
}
Upvotes: 1
Views: 64
Reputation: 717
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
Upvotes: 0
Reputation: 425
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);
}
Upvotes: 1