0

I'm new using PHP, and I'm trying to store functions in an array to call them later using an if statement.

I've tried but, functions are called before if statement, so this is an example of what I need:

    function a()  {
        return 'a';
    }

    function b()  {
        return 'b';
    }

    $array = [a(), b()];

    if($condition === 'a') {
        $array[0];
    }

What I want to achieve is to use a specific function depending on if validation.

Ed Romero
  • 55
  • 9
  • Possible duplicate of [How to call PHP function from string stored in a Variable](https://stackoverflow.com/questions/1005857/how-to-call-php-function-from-string-stored-in-a-variable) –  Apr 29 '19 at 22:00

3 Answers3

0

Just store the function name as a string and call call_user_func.

function a()  {
    return 'a';
}

function b()  {
    return 'b';
}

$array = ['a', 'b'];

if($condition === 'a') {
    call_user_func($array[0]);
}
atoms
  • 2,993
  • 2
  • 22
  • 43
0

Example:

<?php

$funcArray = [
   'a' => function($in) {
      print("$in\n");
   },
   'b' => function($in) {
      print("$in\n");
   }
];

foreach(array_keys($funcArray) as $key)
{
   $funcArray[$key]($key);
}
Chris White
  • 1,068
  • 6
  • 11
0

You'd either have to use call_user_func or use a anonymous function like so:

$array = [
    function() { return 'a'; },
    function() { return 'b'; }
];
Donran
  • 21
  • 3