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

8
  • 2
    Possible duplicate of Execute a function inside array Commented Sep 19, 2017 at 6:39
  • Possible duplicate of Call function in array Commented Sep 19, 2017 at 6:40
  • Possible duplicate of Possible duplicate of Call function in array Commented Sep 19, 2017 at 6: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.....!!!! Commented Sep 19, 2017 at 6:43
  • 1
    Possible duplicate of Call function in array (PHP) Commented Sep 19, 2017 at 7:00

2 Answers 2

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" }
Sign up to request clarification or add additional context in comments.

Comments

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    
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.