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? Thanks!
Edit
Looks like most came up with the same simple solution. Have to give it the first. Thanks everyone!
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.
$arr['ssn'] = $arr['ssn1'] . $arr['ssn2'] . $arr['ssn3'];
unset($arr['ssn1'], $arr['ssn2'], $arr['ssn3']);
I would go with the most naive solution, using a simple concatenation :
$your_array['ssn'] = $your_array['ssn1'] . $your_array['ssn2'] . $your_array['ssn3'];
And you can then unset
the items that are not useful anymore :
unset($your_array['ssn1'], $your_array['ssn2'], $your_array['ssn3']);
Maybe that code looks too naive -- but it's easy to write, and, even more important, very easy to understand.
$data['ssn']=$data['ssn1'].$data['ssn2'].$data['ssn3'];
unset ($data['ssn1'],$data['ssn2'],$data['ssn3']);
You can use implode("",$array) to implode the whole array into a new variable
How about:
implode( array_intersect_key( $array, array_flip(
array_filter( array_keys($array), create_function(
'$k', 'return stristr($k, "ssn");'
)))
)));
This is probably painfully slow compared to just manually concatenating the values, but it was fun to figure out.