mithunsatheesh mithunsatheesh - 1 month ago 4x
PHP Question

changing array keys in array_walk function?

I am using array functions to convert my pipe delimited string to an associative array.

$piper = "|k=f|p=t|e=r|t=m|";

$piper = explode("|",$piper);

$piper = array_filter($piper);

function splitter(&$value,$key) {

$splitted = explode("=",$value);
$key = $splitted[0];
$value = $splitted[1];


array_walk($piper, 'splitter');


this gives me

array (size=4)
1 => string 'f' (length=1)
2 => string 't' (length=1)
3 => string 'r' (length=1)
4 => string 'm' (length=1)

where i want:

array (size=4)
"k" => string 'f' (length=1)
"p" => string 't' (length=1)
"e" => string 'r' (length=1)
"t" => string 'm' (length=1)

but the keys are unaltered. Is there any array function with which i can loop over an array and change keys and values as well?


It's said in the documentation of array_walk (describing the callback function):

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

That means you cannot use array_walk to alter the keys of iterated array. You can, however, create a new array with it:

$result = array();
array_walk($piper, function (&$value,$key) use (&$result) {
    $splitted = explode("=",$value);
    $result[ $splitted[0] ] = $splitted[1];

Still, I think if it were me, I'd use regex here (instead of "exploding the exploded"):

$piper = "|k=f|p=t|e=r|t=m|";
preg_match_all('#([^=|]*)=([^|]*)#', $piper, $matches, PREG_PATTERN_ORDER);
$piper = array_combine($matches[1], $matches[2]);