2
 $numbers = array('1','2');
 $numberlist = foreach($numbers as $number) {
      echo $number;
 } 

As you can see what I'm trying to do it doesn't work is there any other way to store a foreach function as a variable?

3
  • 2
    What exactly are you trying to do? Commented Mar 18, 2011 at 17:08
  • is that $ in front of the echo a typo in the question? Because that will not work :) Commented Mar 18, 2011 at 17:15
  • 1
    I think Matthew is trying to store a procedure or function into a variable. But for starters you'll want to remove the $ in front of 'echo'. Then see the answers below Commented Mar 18, 2011 at 17:15

3 Answers 3

5
$numberList = function( $input )
{
    foreach( $input as $v )
        echo $v;
};

$numberList( $numbers );

See PHP Anon

Note: Anonymous functions are available since PHP 5.3.0.

(The function should be $numberList with a capital L in order for it to work properly.)

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

3 Comments

this only works if you have the newest version of PHP (5.3.x)
I'm using 5.3.5; I used the example you've given me and the variable seems not to be outputting?
@Matthew, I assume you passed in an array when you called the anon function (see last line of example)? Also, that array should contain strings or numbers only. Arrays, booleans, and nulls may print nothing :P
1

If you're trying to store a code reference to the foreach loop in the $numberlist variable, that can't be done: loops are not functions.

If you want an object you can cycle on, you need to build an interator. If this is the case, I suggest you take a look at Standard PHP Library.

Comments

1

I think what Matthew is trying to do is store a function in a variable in PHP. I think this link is what you're looking for:

http://php.net/manual/en/functions.variable-functions.php

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.