1

How can fix error Message: Invalid argument supplied for foreach() - Line Number: 28 in following foreach ?

<?php
$mileage = array();
$mileage_input = $this->input->post('mileage');
foreach ($mileage_input as $idx => $name) {  //Line 28
    $mileage[] = array(
        'mileage' => $mileage_input[$idx]
    );
}
$data = array(
    'mileage' => json_encode($mileage),
    'customer_number' => $customer_number,
    'name' => $this->input->post('name')
);
$this->db->insert('customer', $data);
?>
Jennifer Anthony
  • 2,227
  • 10
  • 37
  • 56

2 Answers2

7

$mileage_input is probably not an array, which is why it isn't working.

Chris G.
  • 3,963
  • 2
  • 21
  • 40
1

Most likely $mileage_input is not an array. Perhaps you must error check $this->input->post.

If you dont really care about the error, but simply want to not get the error you can cast the value to an array before looping over it.

foreach((array)$mileage_input as $idx => $name {
Alexander Olsson
  • 1,908
  • 1
  • 15
  • 24
  • 5
    Hiding the dust under the carpet won't make your house cleaner. – Matteo Riva Sep 20 '11 at 19:57
  • 1
    Very often you can benefit from having e.g. NULL passed to your function, in which case you do not want to do what the loop normally does. Casting NULL to an array gives an empty array and consequently no loops in the foreach will be run. I've found it very useful from time to time. – Alexander Olsson Sep 25 '11 at 13:16
  • 2
    In that case just do an explicit check on the variable being defined and not null. Or, even better, if the function expects an array, pass an array to it (even if it is an empty one). – Matteo Riva Sep 25 '11 at 18:17