0

I couldn't find anything that answers my question so here it is:

I need to have a foreach loop to take each function inside of an array and run each and check if it returns true, simple enough. Like this:

$array_name = array(function1(),function2(),function3());

foreach($array_name as &$value) {
    /* run each function */
    /* checks if it returns true */
}

This may be so easy I just don't see it, but I can't find any definitive documentation on how to correctly implement this.

3 Answers 3

1
$array_name = array('function1', 'function2', 'function3');

foreach($array_name as $value) {
    if($value()) {
        // do stuff if the function returned a true-ish value
    }
}

Another option to call the function would be call_user_func($value).

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

2 Comments

if ($value()) should be if (function_exists()).
He wants to call the function, not check if it exists. In that case it would be function_exists or is_callable.
1

Try it:

$array_name = array('function1','function2','function3');

foreach($array_name as &$value) {
  if(function_exists($value) && ($value())) {
     //function exists and it returns true
  }
}

Comments

0

Try to adopt things from : http://php.net/manual/en/functions.variable-functions.php

foreach($functionName as $arg) {
    $arg();
}

But as you question contains:

$array_name = array(function1(),function2(),function3());

Make sure "function1()" is used in your array. So we can have:

foreach($functionName as $arg) {
   $check = $arg;
   if($check != false){
     //Do stuff here
   }else{
     //Do stuff here
   }
}

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.