1

How To define and execute a function inside array

for example i have a array

    $a="a";
    $b="b";
    $c="c"; 
    $array=array(
         "a"=>$a,
         "b"=>$b,
         "c"=>function($c){
                //do something 
              return output
          }      
    )

here output should be

Array
(
    [a] => a
    [b] => b
    [c] => "new value of c"

)

but actually i am getting

Array
(
    [a] => a
    [b] => b
    [c] => Closure Object
        (
            [parameter] => Array
                (
                    [$c] => 
                )    
        )    
)

NB: i can define a function outside this and call that function inside but i dont want to do that

user3797053
  • 497
  • 1
  • 8
  • 18
  • 2
    Possible duplicate of [Execute a function inside array](https://stackoverflow.com/questions/37195486/execute-a-function-inside-array) – Rahul Sep 19 '17 at 06:39
  • Possible duplicate of [Call function in array](https://stackoverflow.com/questions/9869230/call-function-in-array-php) – Rahul Sep 19 '17 at 06:40
  • Possible duplicate of [Possible duplicate of Call function in array](https://stackoverflow.com/questions/1499862/can-you-store-a-function-in-a-php-array) – Rahul Sep 19 '17 at 06:41
  • I ain't did anything to get these links after searching on internet, I just copy pasted your question title and saw these suggestions of google. Its that easy.....!!!! – Rahul Sep 19 '17 at 06:43
  • @RahulMeshram your 3 links doesnt solved my issue – user3797053 Sep 19 '17 at 06:55
  • You sure, you tried all three, before posting question???? Because it seems, your accepted answer is one from above three links... – Rahul Sep 19 '17 at 06:55
  • 1
    Possible duplicate of [Call function in array (PHP)](https://stackoverflow.com/questions/9869230/call-function-in-array-php) – jcarrera Sep 19 '17 at 07:00
  • Show me exact duplicate all duplicate links here couldnt solve my issue but here i got solution – user3797053 Sep 20 '17 at 08:11

2 Answers2

4

Since closure is a function and it must be executed in order to get a response. Here's how you can execute and return a response

$c = 'awesome';
$array=array(
     "a"=>'test2',
     "b"=> 'test',
     "c"=> call_user_func(function() use ($c) {
            //do something 
          return $c;
      })      
);
var_dump($array);//array(3) { ["a"]=> string(5) "test2" ["b"]=> string(4) "test" ["c"]=> string(7) "awesome" }
Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50
0

Instead of executing the function in an array you can directly assign to some variable and call the function and pass the arguments, then you can use that assigned variable inside your array.

$a="a";
$b="b";
$c="c";
$d = SomeFunction($c); <-- assigning to variable
$array=array(
     "a"=>$a,
     "b"=>$b,
     "c"=> $d    
)
RamaKrishna
  • 219
  • 1
  • 8