0
$arr = array(
    'key1' => 1,
    'key2' => 'value2',
    'key3' => function() {
         if (someConditionSomewhere) {
             return 3;
         } else {
             return 'value3';
         }
    },
);

Let's look at example above. This is what I would love to get in PHP. Create an array, type determinant values there by myself and then for the dynamic value pass a function. I know you can pass anonymous function to arrays since 5.3. But I am not interested in the function alone but rather what it returns. So if I do this later: $arr[key3] I want to get either 3 or 'value3' depending what is there. NOT the function itself.

Is it even possible in PHP?

3
  • not possible you have to call them manually in any lang Commented Aug 25, 2015 at 11:11
  • can you not write the function before and assign it to a variable then put it in an array ? Commented Aug 25, 2015 at 11:12
  • Of course I could. Question purely out of curiosity. :) Commented Aug 25, 2015 at 11:13

3 Answers 3

1

you can check if it's function and then use it

if(is_callable($arr["key3"]))
    $value = $arr["key3"](); //it's function lets add ()
else
    $value = $arr["key3"]; //it's not a function

echo $value; 

or in shorter syntax $value = is_callable($arr["key3"]) ? $arr["key3"]() : $arr["key3"];

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

Comments

1

not possible you have to call them manually in any lang.

$arr[key3] //will return the function reference. so, call that function to execute it. 

//like this.

$arr[key3]();

you can go through more at this answer

2 Comments

I could swear you could do it in JS and JSON. But JSON is actually quite different thing.
no you can't you have to call them in javascript also
0

can you not write the function before and assign it to a variable then put it in an array ?

function test() {
 if (someConditionSomewhere) {
   return 3;
 } else {
     return 'value3';
   }
}
$value = test();

$arr = array(
  'key1' => 1,
  'key2' => 'value2',
  'key3' => $value,
);

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.