Home > Net >  Pass array between functions in Codeigniter
Pass array between functions in Codeigniter

Time:09-28

How can I pass an array from one function to the other one, and add both arrays in Codeigniter?

Here is my code:-

This is the URL of form i use when submit the data.

<form method="POST" action="<?php echo base_url('Welcome/payment_page');?>">


 public function payment(){
    
     $data['userid']  = $this->input->post('userid');
     $data['payment']  = $this->input->post('payment');
        if(!empty($data)){
            $this->payment_page($data); //passing data into another function
         }
         $this->load->view('frontend/include/header');
         $this->load->view('frontend/payment');
    }
    
    
    public function payment_page($data = ''){
       $data;
       
       $other_data=array(
        'cardname' => $this->input->post('cardname'),
           'cardno'=> $this->input->post('cardno'),
          'cardcvv'=> $this->input->post('cardcvv'),
        'cardmonth'=>$this->input->post('cardmonth'),
        'cardyear' =>$this->input->post('cardyear')
        );
        
        $main_data = array_merge($data, $other_data);
        
        
    }

Its giving me error :-

Severity: Warning

Message: array_merge(): Expected parameter 1 to be an array, string given

CodePudding user response:

The parameter you set for payment_page($data = '') is a string, not an array. You have to initialize it with an empty array instead of an empty string So it has to be like

function payment_page($data = [])

CodePudding user response:

Init with an empty array

public function payment_page($data = [])

In case the above code not working, you can try another way.

public function payment_page(&$data = [])

CodePudding user response:

You probably forgot to return the merged array. Try this:

public function payment(){
 $data['userid']  = $this->input->post('userid');
 $data['payment']  = $this->input->post('payment');
    if(!empty($data)){
        $this->payment_page($data); //passing data into another function
     }
     $this->load->view('frontend/include/header');
     $this->load->view('frontend/payment');
 }
 public function payment_page($data){
   $other_data=array(
    'cardname' => $this->input->post('cardname'),
       'cardno'=> $this->input->post('cardno'),
      'cardcvv'=> $this->input->post('cardcvv'),
    'cardmonth'=>$this->input->post('cardmonth'),
    'cardyear' =>$this->input->post('cardyear')
    );
   $main_data = array_merge($data, $other_data);
   return $main_data;
}
  • Related