PHP 8.5.0 Alpha 4 available for testing

Voting

: min(seven, nine)?
(Example: nine)

The Note You're Voting On

r
7 years ago
How to modify external variable from inside recursive function using userdata argument.

<?php
$arr
= [
'one' => ['one_one' => 11, 'one_two' => 12],
'two' => 2
];

$counter = 0;

//Does not persist
array_walk_recursive( $arr, function($value, $key, $counter) {
$counter++;
echo
"$value : $counter";
},
$counter);
echo
"counter : $counter";

// result
// 11 : 1
// 12 : 1
// 2 : 1
// counter: 0

//Persists only in same array node
array_walk_recursive( $arr, function($value, $key, &$counter) {
$counter++;
echo
"$value : $counter";
},
$counter);

// result
// 11 : 1
// 12 : 2
// 2 : 1
// counter : 0

//Fully persistent. Using 'use' keyword
array_walk_recursive( $arr, function($value, $key) use (&$counter) {
$counter++;
echo
"$value : $counter";
},
$counter);
echo
"counter : $counter";

// result
// 11 : 1
// 12 : 2
// 2 : 3
// counter : 3

<< Back to user notes page

To Top