Abuzettin
Abuzettin

Reputation: 3

When variable to define a PHP function in foreach, returns last item

foreach ( $keys as $key ){
    $key['function_name'] = function (){
        global $key;
        $return = '<h3>'. $key['title'] .'</h3>';
        return $return;
     };
    // do someting with return.
}

when I do someting with return it always return me last title of $keys. What I need to do for getting specific title which I want with "$key['function_name']"

Upvotes: 0

Views: 43

Answers (1)

axiac
axiac

Reputation: 72256

The statement:

$key['function_name'] = function (){
    global $key;
    $return = '<h3>'. $key['title'] .'</h3>';
    return $return;
 };

stores in $key['function_name'] a function object. The code of the function is not executed at that point.

You run the function later, I guess after the foreach. When it runs, it expects to find the global variable $key that probably is the one you use to iterate over $keys. Since the iteration over $keys already completed, the value of $key is the last value assigned to it during the foreach.

The correct solution is to bind the current value of $key to the function using the use keyword:

foreach ($keys as $key) {
    $key['function_name'] = function () use ($key) {
        return '<h3>'. $key['title'] .'</h3>';
     };
}

This way each function created during the foreach uses a different $key: the value of $key that was current when the function was created.

Upvotes: 2

Related Questions