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

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



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
Updated on: 2020-10-12T13:20:17+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements