Search code examples
phparraysdry

DRY array in php


Hello I am trying to apply the DRY concept to my program which now has over 3000 lines of codes just because i have been repeating myself a lot.

I have this array:

// prepare the sales payload
$sales_payload = array(
    'organization_id' => $getOrg['data'][0]['id'],
    'contact_id' => $contact_id,
    'status' => 'Open',
    'responsible_employee_id' => 'employee:50c76c15262b12d36d44e34a3f0f8c3d',
    'source' => array(
    'id' => $source['data'][0]['id'],
    'name' => $source['data'][0]['name'],
    ),
    'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - "."Online marketing Duitsland",
    'start_date' => date("Y-m-d"), // set start date on today
    'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now
    'chance_to_score' => '10%',
    'expected_revenue' => 0, //set the expected revenue
    'note' => $_POST['order_comments'],
    'progress' => array(
    'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress 
    ),

  "custom_fields" => [["voorstel_diensten"=>implode("-",$online_marketing_check)]],

);

Is there a way I can dynamically change certain fields only instead of copying the whole thing and manually changing it.


Solution

  • You can declare a function that clones the array and changes it

    function arrayClone($args){
        $sales_payload = array(
            'organization_id' => $getOrg['data'][0]['id'],
            'contact_id' => $contact_id,
            'status' => 'Open',
            'responsible_employee_id' => 'employee:50c76c15262b12d36d44e34a3f0f8c3d',
            'source' => array(
            'id' => $source['data'][0]['id'],
            'name' => $source['data'][0]['name'],
            ),
            'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - "."Online marketing Duitsland",
            'start_date' => date("Y-m-d"), // set start date on today
            'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now
            'chance_to_score' => '10%',
            'expected_revenue' => 0, //set the expected revenue
            'note' => $_POST['order_comments'],
            'progress' => array(
            'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress 
            ),
    
          "custom_fields" => [["voorstel_diensten"=>implode("-",$online_marketing_check)]],
    
        );
    
        return array_replace_recursive($sales_payload, $args);
    }
    

    How tu use it:

    $a = arrayClone(['status' => 'Closed', 'contact_id' => 5]);
    $b = arrayClone(['status' => 'Closed Now', 'contact_id' => 20]);