简体   繁体   中英

PHP array_walk doesn't work properly

I've read a lot of posts related to array_walk but I can't fully understand why my code doesn't work. Here is my example.

The $new_array is empty when I do the var_dump , If I write var_dump on every iteration it shows some value, meaning that is treating the $new_array as a new variable on every iteration, I don't know why this is.. Does anyone know what is the error occurred in this code ?

$exploded = explode(",", $moveArray[0]);

print_r($exploded);

$new_array = array();
array_walk($exploded,'walk', $new_array);

function walk($val, $key, &$new_array){
    $att = explode('=',$val);
    $new_array[$att[0]] = $att[1];

}

var_dump($new_array);

Do it like this.

$new_array = array();
array_walk($exploded,'walk');

function walk($val, $key){
    global $new_array;
    $att = explode('=',$val);
    $new_array[$att[0]] = $att[1];

}

Looking into your code I've found that your issue is to parse something like: a=b,c=d,e=f . Actually, since your question is about using array_walk() , there's correct usage:

$string = 'foo=bar,baz=bee,feo=fee';

$result = [];
array_walk(explode(',', $string), function($chunk) use (&$result)
{
   $chunk = explode('=', $chunk);
   $result[$chunk[0]]=$chunk[1];
});

-ie to use anonymous function , which affects context variable $result via accepting it by reference.

But your case, in particular, even doesn't require array_walk() :

$string = 'foo=bar,baz=bee,feo=fee';

preg_match_all('/(.*?)\=(.*?)(,|$)/', $string, $matches);
$result = array_combine($matches[1], $matches[2]);

-or even:

//will not work properly if values/names contain '&' 
$string = 'foo=bar,baz=bee,feo=fee';
parse_str(str_replace(',', '&', $string), $result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM