Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 876967
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:31:32+00:00 2026-05-15T11:31:32+00:00

PROBLEM I have a nested PHP array that I need to populate from flat

  • 0

PROBLEM

I have a nested PHP array that I need to populate from flat scalar
values. The problem is I cannot know ahead of time what the structure
of the nested PHP array will be until I get the request to fill in
the flat scalar values.

EXAMPLE

// example where we populate the array using standard PHP
$person['contact_info']['fname']  = 'Attilla';
$person['contact_info']['lname']  = 'Hun';
$person['contact_info']['middle'] = 'The';    
$person['hobbies'][0]             = 'Looting';
$person['hobbies'][1]             = 'Pillaging';

// example where we populate the array from flat scalar values
// (these are obtained from the user via name-value pairs)

// how can I correctly populate $person from this??
print($_GET['contact_info.fname']);   // 'Smokey';
print($_GET['contact_info.middle']);  // 'The';
print($_GET['contact_info.lname']);   // 'Bear';

// how can I correctly populate $person from this??
print($_GET['contact_info.fname']);   // 'Jabba';
print($_GET['contact_info.middle']);  // 'The';
print($_GET['contact_info.lname']);   // 'Hutt';

// How can I use these three flat scalars 
// to populate the correct slots in the nested array?

QUESTION

I know I must not be the first person who has needed to convert from flat name-value pairs into a nested PHP array (or nested array in any programming language). What is the established way (if any) of converting these flat scalar name-value pairs into the appropriate PHP nested array?

Just to re-iterate, I cannot know ahead of time what the name-value pairs will be for populating the array, that is one constraint I am dealing with here.

UPDATE

The fact that I cannot know the values (or, if you prefer, the Array keys that get populated by the scalar-value-representations) is a constraint of the particular problem space I am dealing with. This is not a question about basic PHP array syntax.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:31:33+00:00Added an answer on May 15, 2026 at 11:31 am

    Note: My PHP code below is a hack, instead do this. Someone had posted a better solution earlier, but the post is gone now. In short, you can already submit arrays of values in forms to PHP:

    <form ...>
    <input type="text" name="contact_info[fname]">
    <input type="text" name="contact_info[lname]">
    <input type="text" name="contact_info[middle]">
    </form>
    

    The square brackets in the name attribute do exactly what you think they might do. On submit, $_POST['contact_info'] will be an array with three keys, fname, lname, and middle.

    If at all possible, you should use this method rather than the code I’ve written below. It’s cleaner, it’s better, it’s more maintainable, it’s the way it should be done.


    This is a fun challenge. We’re going to use PHP’s funny way of doing references to our advantage. Given that:

    • $input is an array that contains only key/value pairs that are for $person
    • A period is always the separator character
    • You will never encounter a key that has both array and non-array values, i.e. there will never be both ‘contact_info’ and ‘contact_info.foo’

    Then this function might be a starting point for you.

    function nifty_splitty_magicky_goodness($input) {
    // Start out with an empty array.
        $person = array();
        foreach($input as $k => $v) {
        // This turns 'a.b' into array('a', 'b')
            $key_parts = explode('.', $k);
        // Here's the magic.  PHP references aren't to values, but to
        // the variables that contain the values.  This lets us point at
        // array keys without a problem.  Sometimes this gets in the way...
            $ref = &$person;
            foreach($key_parts as $part) {
            // If we didn't already turn the thing we're refering to into an array, do so.
                if(!is_array($ref))
                    $ref = array();
            // If the key doesn't exist in our reference, create it as an empty array
                if(!array_key_exists($part, $ref))
                    $ref[$part] = array();
            // Reset the reference to our new array.
                $ref = &$ref[$part];
            }
        // Now that we're pointing deep into the nested array, we can
        // set the inner-most value to what it should be.
            $ref = $v;
        }
        return $person;
    }
    
    // Some test data.    
    $input = array(
        'a.b' => 1,
        'a.c' => 2,
        'a.d.e' => 3,
        'f' => 4,
        'g.h' => 5
    );
    // Run it!
    var_export(nifty_splitty_magicky_goodness($input));
    // Should produce:
    array (
      'a' => 
      array (
        'b' => 1,
        'c' => 2,
        'd' => 
        array (
          'e' => 3,
        ),
      ),
      'f' => 4,
      'g' => 
      array (
        'h' => 5,
      ),
    

    Again, this is a hack. You should use PHP form handling to take care of this for you.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 494k
  • Answers 494k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Your unique index have some name, use: ALTER TABLE `advertisements`… May 16, 2026 at 11:07 am
  • Editorial Team
    Editorial Team added an answer Here's a link to the usage. Returns a consistent, platform-independent… May 16, 2026 at 11:07 am
  • Editorial Team
    Editorial Team added an answer You can try: ddItems.Items.FindByText("Hello, World!").Selected = true; Or: ddItems.SelectedValue =… May 16, 2026 at 11:07 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

here i am again ;) My problem atm is with nested php classes, i
I have a problem with my database class. I have a method that takes
I have a multi-dimensional multi-object array from a simplexml_import_dom() function call. A slice of
Problem: We have to read from a proprietary binary file at work. It changes
I have a major problem. We have a asp.net application that has this report
I have this PHP code I am trying to integrate with the html layout
Can someone please confirm that the following is a bug with PHP 5.2.13: (thank
I have a configurable report. For each field that can be included on the
I have problem with refering to special symbol in string: I have: path='C:\dir\dir1\dir2\filename.doc' and
I have problem concerning translations in qt. All translations in my porject work fine,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.