Last active
November 13, 2022 04:40
-
-
Save mejdzer/6813472 to your computer and use it in GitHub Desktop.
Split a string by string and put into an associative array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Explode the strings delimited with a given string/character | |
* into an associative array. | |
* | |
* Function alters $new_array associative array passed to the function | |
* by reference. This array should contain keys and values. Example.: | |
* $new_array = array( | |
* 'bananas' => '', | |
* 'strawberries' => '', | |
* 'water mellons' => '' | |
* ); | |
* | |
* For a given $string = 'are yellow|are red|are green|are black' and $delimiter = '|' | |
* we will get $new_array: | |
* [bananas] => 'are yellow', | |
* [strawberries] => 'are red', | |
* [water mellons] => 'are green', | |
* [3] => 'are black' | |
* | |
* @param string $delimiter Delimiter. | |
* @param string $string Source string. | |
* @param array $new_array Assiciative array. | |
* @return void. | |
*/ | |
function explodeToAssoc($delimiter, $string, &$new_array) | |
{ | |
$array = explode($delimiter, $string); | |
$nkeys = array_keys($new_array); | |
array_walk($array, function($value, $key, $nkeys) use(&$new_array) { | |
if (isset($new_array[$nkeys[$key]])) { | |
$new_array[$nkeys[$key]] = $value; | |
} else { | |
$new_array[$key] = $value; | |
} | |
}, $nkeys); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment