1

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

2 Answers 2

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

-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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

}

1 Comment

global? are you joking?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.