Aaron
Aaron

Reputation: 11673

foreach array function storing in a variable?

 $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?

Upvotes: 2

Views: 2029

Answers (3)

Kevin Peno
Kevin Peno

Reputation: 9196

$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.)

Upvotes: 5

Mala
Mala

Reputation: 14803

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

Upvotes: 1

Matteo Riva
Matteo Riva

Reputation: 25060

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.

Upvotes: 1

Related Questions