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
Post a Comment