PHP, is it possible to use an anonymous function in array to get certain value? -


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

let's @ example above. love in php. create array, type determinant values there myself , dynamic value pass function. know can pass anonymous function arrays since 5.3. not interested in function alone rather returns. if later: $arr[key3] want either 3 or 'value3' depending there. not function itself.

is possible in php?

you can check if it's function , use it

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

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


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -