changing array keys in array_walk function?
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];
});
var_dump($result);
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]);
var_dump($piper);
Using array_reduce will do the trick
$piper = "|k=f|p=t|e=r|t=m|";
$piper = explode("|",$piper);
$piper = array_filter($piper);
function splitter($result, $item) {
$splitted = explode("=",$item);
$key = $splitted[0];
$value = $splitted[1];
$result[$key] = $value;
return $result;
}
$piper = array_reduce($piper, 'splitter', array());
var_dump($piper);
based on this: http://www.danielauener.com/howto-use-array_map-on-associative-arrays-to-change-values-and-keys/
You can better use foreach
for that. The following example shows processing an entry, adding it with the right key and deleting the original entry.
$piper = "|k=f|p=t|e=r|t=m|";
$piper = array_filter(explode("|", $piper));
foreach ($piper as $index => $value) {
list($key, $value) = explode("=", $value);
$piper[$key] = $value;
unset($piper[$index]);
}
Take care you do not have keys that are like an index.
Another alternative is to process the values via a reference and set the keys afterwards:
foreach ($piper as &$value) {
list($keys[], $value) = explode("=", $value);
}
unset($value);
$piper = array_combine($keys, $piper);
This does not bring you into any troubles but just with duplicate keys. But you could check for that problem after the foreach
, no data would be lost.
Something that can not be guaranteed with the following foreach
which probably is the most simplified by stroing into a result array:
$result = array();
foreach ($piper as $value) {
list($key, $value) = explode("=", $value);
$result[$key] = $value;
}
Why not build a new array that has the desired keys and values from $piper?
$piper2 = array();
foreach ($piper as $k => $val)
{
$splitted = explode("=", $val);
$key = $splitted[0];
$value = $splitted[1];
$piper2[$key] = $value;
}
$piper = $piper2; // if needed