Nash
Nash

Reputation: 375

Add array conditionally as a variable in an another array conditionally

This is how the final output of the array should look like

$dataToReset = array (
    'email_address' => $subEmail,
    'status' => 'subscribed',
    'interests' => 
        array (
        '1111111' => true,
        '2222222' => true,
        '3333333' => true,
        '4444444' => true,
        '5555555' => true,
    )
);

I want to replace following part

'interests' => 
    array (
    '1111111' => true,
    '2222222' => true,
    '3333333' => true,
    '4444444' => true,
    '5555555' => true,
)

With a variable $interestsAdd like this

$dataToReset = array (
    'email_address' => $subEmail,
    'status' => 'subscribed',
    $interestsAdd
);

The values that i get and what i have tried is like following, but no success!

if ($form_data['lbu_multilistsvalue'] !== ''){
    
    $groupsSelected = $form_data['lbu_multilistsvalue'];
    $selectedGroups = array_fill_keys(explode(",", $groupsSelected), true);

    $interestsAdd = ['interests' => $selectedGroups];

} else {

    $interestsAdd = '';

}

Upvotes: 1

Views: 31

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

You have several options, either define the key in the array:

$interestsAdd = [1,2,3];

$dataToReset = array (
    'email_address' => 'x',
    'status' => 'subscribed',
    'interests' => $interestsAdd
);

Or add it afterwards:

$interestsAdd = [1,2,3];

$dataToReset = array (
    'email_address' => 'x',
    'status' => 'subscribed',
);
$dataToReset['interests'] = $interestsAdd;

Or with your current structure, merge them:

$interestsAdd = ['interests' => [1,2,3]];

$dataToReset = array_merge($dataToReset, $interestsAdd);

Upvotes: 1

j4g0
j4g0

Reputation: 198

Try setting up your first array like this:

$dataToReset = [
    'email_address' => $subEmail,
    'status' => 'subscribed',
    'interests' => [],
];

Once you have your $interestsAdd array built you add it to the first array:

$dataToReset['interests'] = $interestsAdd;

Upvotes: 0

Related Questions