user3797053
user3797053

Reputation: 517

Define and execute function inside php array

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

Upvotes: 1

Views: 8340

Answers (2)

Basheer Kharoti
Basheer Kharoti

Reputation: 4292

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" }

Upvotes: 4

RamaKrishna
RamaKrishna

Reputation: 217

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    
)

Upvotes: 0

Related Questions