2

I have two functions and want to when $test=one, function1() runs and when $test=two, function2() runs. Like this:

switch ($test)
 {

case "one":
function1();
break;

case "two":
function2();
break;

 }

Now how do it (selecting) via array? any body know?

how set key of array on function ? something like this:

array("one"=>function1(),"two"=>function2());
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

4
<?php
function func1()
{
    print "111\n";
}

function func2()
{
    print "222\n";
}

//put functions names into an array
$functions = array(
    'one' => "func1",
    'two' => "func2",
);

$test = 'two';

if(isset($functions[$test]))
{
    call_user_func($functions[$test]);
}

Output:

222

http://php.net/manual/en/function.call-user-func.php

user4035
  • 22,508
  • 11
  • 59
  • 94
  • your solution is great, but i don't want any `if` and function like `call_user_func();` . anyway tnx for Training `call_user_func();` to me. :) –  Apr 18 '15 at 15:23
  • can you tell me which one is better ? `call_user_func($functions[$test]);` OR `$functions[$test]();` –  Apr 18 '15 at 15:50
  • @Fatemeh It's actually the same - php has to search for the function with appropriate name in it's functions table. The difference is only in syntax. – user4035 Apr 18 '15 at 17:29
0

The answer of user4035 is correct, but in other word we can use:

$arr[$test]();

instead

call_user_func($arr[$test]);

then: (full code) :

  function func1(){
    echo 'func1 runing';
        }

  function func2(){
    echo 'func2 runing';
        }

     $test='one';

     $arr=array ('one'=>'func1','two'=>'func2');
     $arr[$test]();

output:

func1 runing