0

Let's say I have the following example code:

<?php

$arr = array(0 => array(0 => 1, 1 => 2), 1 => 3);
$val = '';

function test($item, $key){
    if($key === 0){
        $val = 'found';
    }
}

array_walk_recursive($arr, 'test');

?>

Obviously $val is out of scope for test(). Instead it just sets $val inside the function and destroys it as soon as it's done. How would I set the value outside of the function from within it?

Note: I'm pretty sure this is something simple that I should know. Been working for hours and just can't wrap my head around it anymore. Hope you guys can help me out. Thanks in advance!

icecub
  • 8,615
  • 6
  • 41
  • 70
  • 2
    Use an anonymous function: `array_walk_recursive($arr, function ($item, $key) use (&$val) { ... })`. Without an anonymous function and `use` the workaround would involve classes and is a bit too overblown. – deceze Jul 25 '18 at 09:54
  • @deceze Ah of course! Thanks a lot! – icecub Jul 25 '18 at 09:56

0 Answers0