Jennifer Anthony
Jennifer Anthony

Reputation: 2277

Error Undefined offset

I want insert following checkbox in a row from database table, but have error, how is fix it? (I can not change 5 in name checkbox)

<input type="checkbox" name="checkbox_units_a[5][]" value="tv">
<input type="checkbox" name="checkbox_units_a[5][]" value="radio">

$name_un = $this -> input -> post('name_units_a');
$service_un = $this -> input -> post('checkbox_units_a');
$data3 = array();
foreach($name_un as $idx => $name) {
    $data3[] = array(
    'name_un' => $name_un[$idx],
    'service_un' => json_encode($service_un[$idx]), ); //This is line 210
};
$this -> db -> insert_batch('hotel_units', $data3);

Error:

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: residence.php
Line Number: 210

My output in var_dump from $name_un:

array(1) {
    [0] = > string(6)"accessories"
}

My output in var_dump from $service_un:

array(1) {
    [5] = > array(2) {
        [0] = > string(15)"tv" [1] = > string(12)"radio"
    }
}

Upvotes: 0

Views: 2998

Answers (2)

veritas
veritas

Reputation: 2052

Error says your offset is equal 0 propably your $idx == 0 and $service_un[$idx] == null ;)

EDIT

As I thought $idx == 0 is causing undefined offset 0 in json_encode try to reindex your $service_un array (if you cannot change the 5 in HTML) to make it start with 0 example:

$service_un = array_values ( $service_un ); // reindexing array

it will look like:

array(1) {
  [0] => array(2) {
    [0] => string(2) "tv"
    [1] => string(5) "radio"
  }
}

Upvotes: 1

RiaD
RiaD

Reputation: 47619

$service_un have only one offset, and it's five(5), So 0 is undefined here.

Upvotes: 0

Related Questions