1

I am trying to loop through an array using foreach loops and for each elements I want to create a separate function.

$items = ['one', 'two', 'three'];

foreach( $items as $item ){
    function $item."_output"(){
        echo $item.' success';
    }
}

My expectation is to create function for each array element like: function one_output(){}, function two_output(){}, function three_output(){}

7
  • 1
    Why you need this? Commented Sep 25, 2020 at 14:12
  • I am trying to make a WordPress plugin where I have to deal with this issue. Commented Sep 25, 2020 at 14:23
  • What’s the issue? Commented Sep 25, 2020 at 14:29
  • Does this answer your question? Creating a function name on the fly (dynamically) - PHP Commented Sep 25, 2020 at 14:30
  • 1
    You can't create named functions from variables without using eval, because function names are identifiers which must exist when the PHP interpreter parses the code, and creating things using variable values happens at runtime. You can create anonymous functions using variable variables, but that may not work for what you're trying to do. Will these functions be used as callbacks in your WP plugin? I think there may be a better way to do this. Commented Sep 25, 2020 at 14:38

1 Answer 1

1

You cannot create functions directly. But instead you can create closures (anonymous functions) and put them into an array:

<?php
  $items = ['one', 'two', 'three'];

  $myfuncs = array();

  foreach( $items as $item ) {
      // create a function which uses current value of $item
      $myfuncs[$item] = function() use ($item) { 
         echo  $item.' success';
      };
  }

  $myfuncs['one'](); // one success

  $myfuncs['two'](); // two success
Sign up to request clarification or add additional context in comments.

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.