Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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( );

Use a closure:

$function = function($array){

    foreach($array as $var){

        // do your stuff

    }

};

$function($yourArray);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top