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());
6
  • Please add an example how you want to use it then! Commented Apr 18, 2015 at 14:49
  • I want: when $test=one then echo 'one', and when $test=two then echo 'two'. using array php Commented Apr 18, 2015 at 14:52
  • no, echo string of 'test', or run a function. Commented Apr 18, 2015 at 14:58
  • It's not at all clear what you're asking for here ? Commented Apr 18, 2015 at 15:00
  • 1
    @halfer tnx for editing. Commented Apr 18, 2015 at 15:31

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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. :)
can you tell me which one is better ? call_user_func($functions[$test]); OR $functions[$test]();
@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.
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

Comments