Home > OS >  php - Adding multiple values to an array using foreach
php - Adding multiple values to an array using foreach

Time:10-22

I'm saving multiple values on form submit to an array using foreach. The below logic was working fine before php 8 update.

Please let me know what needs to be done to make it work again.

$batch = $this->input->post('batch_id');
$activity_selected = $this->input->post('activity_selected');
$characteristics = array_values($this->input->post('characteristics'));
$user_id=$this->session->userdata('userid');
foreach($activity_selected as $key => $val) 
{
    $dataSet[] = array (
            'batch_id' => $batch_id,
            'activity_id' => $activity_selected[$key],
            'characteristics' => implode(',', $characteristics[$key]),
            'user_id' => $user_id,
    );  
}
$this->person->insertdata($dataSet,$batch);

Getting this error

ERROR - 2222 Oct 2121 11:47:24 --> Severity: Compile Error --> Cannot use [] for reading D:\xampp\htdocs*** 122

ERROR - 2222 Oct 2121 11:47:32 --> Severity: error --> Exception: implode(): Argument #2 ($array) must be of type ?array, string given D:\xampp\htdocs*** 108 ERROR - 2222 Oct 2121 11:47:32 --> Severity: error --> Exception: implode(): Argument #2 ($array) must be of type ?array, string given D:\xampp\htdocs*** 108

CodePudding user response:

Prior to PHP 8, the following code would throw only a warning and return NULL

See here. https://3v4l.org/vuNBL

$characteristics['key'] = 'string';
$key = 'key';

var_dump(implode(',', $characteristics[$key]));

// Warning: implode(): Invalid arguments passed in /in/q6EPW on line 6
// NULL

Since PHP 8, the warning is now elevated to a Fatal error

Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given

There are a couple of ways you can resolve this, the easiest would be to check if the value is an array, and if not pass an empty array.

implode(',', is_array($characteristics[$key]) ? $characteristics[$key] : []);

// string(0) ""

CodePudding user response:

There isn't a massive amount you could do to that code, you could get rid of the need to have an incremental variable ($i) by using foreach($items as $key => $value) and using $key instead of $i.

  •  Tags:  
  • php
  • Related