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'); var_dump($piper);
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?
The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.
The function returns an array in flip order, i.e. keys from array become values and values from array become keys. Note: The values of the array need to be valid keys, i.e. they need to be either integer or string.
The array_walk() function runs each array element in a user-defined function. The array's keys and values are parameters in the function. Note: You can change an array element's value in the user-defined function by specifying the first parameter as a reference: &$value (See Example 2).
The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With