Skip to content

Instantly share code, notes, and snippets.

@carolosf
Last active April 12, 2023 09:06
Show Gist options
  • Save carolosf/66dcbcf7e9063528f8cc518e57e2c3b4 to your computer and use it in GitHub Desktop.
Save carolosf/66dcbcf7e9063528f8cc518e57e2c3b4 to your computer and use it in GitHub Desktop.
Explode To Nested Array - Converts a string with a delimiter into a nested associative array and assigns the value to the final key
<?php
/**
* Converts a string with a delimiter into a nested associative array and assigns the value to the final key
* by Carolos Foscolos - I call this little algorithm bubble wrap - because it's like wrapping bubbles around each other
* explodeToNestedArray('.', 'abc.def', 'XYZ') becomes ['abc' => ['def' => 'XYZ']]
*
* @param string $delimiter
* @param string $key
* @param $value
*
* @return array {
* @var string Field names
* @var mixed Values relating to fields.
* }
*/
function explodeToNestedArray($delimiter, $key, $value)
{
$keys = explode($delimiter, $key);
while ($key = array_pop($keys)) {
$value = [$key => $value];
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment