How to build dynamic associative array from simple array in php?

PHPServer Side ProgrammingProgramming

Let’s say we have the following array −

$namesArray = ['John', 'Adam', 'Robert'];

We want the following output i.e. an associative array from the above array −

Array ( [John] => Array ( [Adam] => Array ( [Robert] => Smith ) ) )

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
function buildingDynamicAssociativeArray($nameArr, $lastName) {
   if (!count($nameArr)) {
      return $lastName;
   }
   foreach (array_reverse($nameArr) as $key) {
      $dynamicAssociativeArr = [$key => $lastName];
      $lastName = $dynamicAssociativeArr;
   }
   return $dynamicAssociativeArr;
}
$namesArray = ['John', 'Adam', 'Robert'];
$result = buildingDynamicAssociativeArray($namesArray, 'Smith');
print_r($result);

$namesArray = [];
$result1 = buildingDynamicAssociativeArray($namesArray, 'Doe');
echo "";
print_r($result1);
?>
</body>
</html>

Output

Array ( [John] => Array ( [Adam] => Array ( [Robert] => Smith ) ) )
Doe
raja
Published on 12-Oct-2020 13:18:59
Advertisements