Search code examples
phparraysmerging-data

Consolidate the string values of elements with the same key prefix


Not sure if there is a built in function to do this, so I thought I would ask before I waste the time of writing one. Lets say I have an array:

Array
    (
        ['first_name'] => John
        ['last_name'] => Doe
        ['ssn1'] => 123
        ['ssn2'] => 45
        ['ssn3'] => 6789
    )

How can I create new key ['ssn'] which will combine the values of the other three, to result in the following:

Array
    (
        ['first_name'] => John
        ['last_name'] => Doe
        ['ssn'] => 123456789
    )

It comes in separated because there are 3 separate inputs like such [   ]-[  ]-[    ] to keep the user from screwing it up. So, what would be the most effective/elegant way of doing this?


Solution

  • Assuming this data comes from a web form, you could use the input naming convention to your advantage. Name the elements in order first_name, last_name, ssn[1], ssn[2], ssn[3]. $_REQUEST will automatically assign the three elements to a structured array.

    <input type="text" name="ssn[1]" />
    <input type="text" name="ssn[2]" />
    <input type="text" name="ssn[3]" />
    
    array
      'ssn' => 
        array
          1 => string '123' (length=3)
          2 => string '456' (length=3)
          3 => string '7890' (length=4)
    

    Then you can simply

    $_POST['ssn'] = implode('-', $_POST['ssn']);
    

    Simple and clean.