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




 $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);
?>

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