In php is possible to access elements of the current Array by index?

arrays, php

Solution

The problem here is that `$arr` is a variable defined outside the function, so it cannot be accessed from within the function.

It's tempting to try to just import the `$arr` variable into the closure using `use ($arr)`, but that won't work because `$arr` isn't actually defined at the time you're defining your function.

As long as `$arr` is really a global varable, you can update the function like this to make it work:

'index2' => function() {
    global $arr;
    $arr['index1'](); // foo
    echo 'bar';  //bar
}

A better idea, though, is to pass the array in as a parameter to the function, like this:

'index2' => function($a) {
    $a['index1'](); // foo
    echo 'bar';  //bar
}

...and call it like this:

$arr['index2']($arr);

Problem

In php is possible to access elements of the current Array by index? Example: ``` $arr = array( 'index1' => function() { echo 'foo'; //foo }, 'index2' => function() { $arr['index1']() // foo ?????????? echo 'bar'; //bar } ); ``` how to call `$arr['index1']()` in `$arr` ?

Original source