user2906838
user2906838

Reputation: 1178

How to map two array in php so that to get a combined array as a result?

I've two array, something like this,

form_field_combined = ["920" => "920", "921" => "921", "922" =>"922", "923" => "923", "924" => "924", "925" => "925", "926" => "926"];

And next array is something like this,

$values = ["920"=>"Answer", "924" => "Option", "926"=>"Something Awesome"];

Note: The length of second array $values is always be equal to or less than the first array $form_field_combined .

Now What I want to achieve is, a combined array from these two array, so that it would look something like this.

$new_array = ["920"=>"Answer", "921"=>"", "922" => "", "923"=>"", "924" => "Option", "925" => "", "926"=>"Something Awesome"];

My solution would be to use array_map something like this:

            $form_data_values = [];
            $all_fields = array_map(function ($each, $key) use ($values, $form_data_values) {

                array_map(function ($each_value, $each_key) use ($each, $key, $values, $form_data_values) {

                    if (in_array($each, $values)) {
                        array_push($form_data_values, [$key => $values[$each]]);

                    } else {
                         array_push($form_data_values, [$key => ""]);
                    }
                    dd($form_data_values);   // The values are as expected and being preserved here.. 
                }, $values, $form_data_values);

                dd($form_data_values); // The value is lost now, and is blank.
            }, $values, array_keys($form_field_combined));

I want that $form_data_values array to be preserved, so that I could use that elsewhere, which in my case not working.

Or You could see the expected result and propose any other way around. Thank You

Upvotes: 0

Views: 47

Answers (1)

William Buttlicker
William Buttlicker

Reputation: 6000

This will do it.

$result = array();
foreach ($form_field_combined as $key => $val) {
    $result[$key] = !empty($values[$key]) ? $values[$key] : "";
}

For preserving 0 use isset

$result = array();
    foreach ($form_field_combined as $key => $val) {
        $result[$key] = isset($values[$key]) ? $values[$key] : "";
    }

Upvotes: 2

Related Questions