How can PHP developers efficiently iterate through exploded data to create array keys and values for a nested structure?

When iterating through exploded data in PHP to create array keys and values for a nested structure, developers can efficiently achieve this by using a combination of foreach loops and conditional statements. By checking the depth of the nested structure during iteration, developers can dynamically create array keys and assign values accordingly.

$data = "first.second.third.value";
$explodedData = explode(".", $data);

$result = [];
$currentArray = &$result;

foreach ($explodedData as $key => $value) {
    if ($key < count($explodedData) - 1) {
        if (!isset($currentArray[$value])) {
            $currentArray[$value] = [];
        }
        $currentArray = &$currentArray[$value];
    } else {
        $currentArray[$value] = "desired_value";
    }
}

print_r($result);