1

In order to pass an array in the code of create_function(), passing it to the parameter works,

$array = array('a', 'b', 'c');

$func = create_function('$arr', '
            foreach($arr as $var) echo "$var<br />";
        ');

$func($array);

But I'd like to embed an array in the code directly like the eval() capability. Like this,

$array = array('a', 'b', 'c');
eval( 'foreach($array as $var) echo "$var<br />";');

However, this doesn't work.

$array = array('a', 'b', 'c');

$func = create_function('', '
            foreach(' . $array . ' as $var) echo "$var<br />";
        ');

$func();

So how do I do it? Thanks for your info.

Teno
  • 2,582
  • 4
  • 35
  • 57

4 Answers4

2

In case you insist on create_function instead of lambda functions

$func = create_function('', '
  foreach(' . var_export($array, true) . ' as $var) echo "$var<br />";
');

You need a (valid) string representation of the array for the php parser. var_export provides that.
But Berry Langerak's answer is the way to go.

Community
  • 1
  • 1
VolkerK
  • 95,432
  • 20
  • 163
  • 226
1

When using PHP >= 5.3, you can use an anonymous function instead of create_function. The anonymous function can "use" a variable from the outer scope.

<?php
$array = array('a', 'b', 'c');

$func = function( ) use( $array ) {
    foreach( $array as $value ) {
        echo $value;
    }
};

$func( );
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • Thanks, it works beautifully on my test server. Some of the servers I'm using are below PHP v5.3 unfortunately. – Teno Sep 20 '12 at 10:56
  • 2
    @Teno I'm sorry to tell you, but in that case some of the servers you're using are using software that's not supported and should be upgraded. PHP 5.2 end of support was in December 2010. ;) – Berry Langerak Sep 20 '12 at 11:30
  • Oh really... They are free shared hosts so I cannot do anything about it. Thanks for telling me that. – Teno Sep 20 '12 at 11:35
0

Use a closure:

$function = function($array){

    foreach($array as $var){

        // do your stuff

    }

};

$function($yourArray);
moonwave99
  • 21,957
  • 3
  • 43
  • 64
-1

I'm posting this only for educational purposes (it's very bad practice):

<?php

$array = array('a', 'b', 'c');

$func = create_function('', '
            global $array;
            foreach($array as $var) echo "$var<br />";
        ');

$func();

Why is it so awfull?

  • global variables
  • ugly way to create a function

If your version of PHP is at least 5.3 then use lambda function. See @Berry Langerak answer

Vlad Balmos
  • 3,372
  • 19
  • 34