Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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
Advertisements