Gabriel Matusevich
Gabriel Matusevich

Reputation: 3855

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);

Upvotes: 1

Views: 139

Answers (2)

Alma Do
Alma Do

Reputation: 37365

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];
});

-i.e. 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);

Upvotes: 1

zzlalani
zzlalani

Reputation: 24364

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];

}

Upvotes: 1

Related Questions