Invalid argument supplied for foreach()
27,143
Solution 1
$mileage_input
is probably not an array, which is why it isn't working.
Solution 2
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 {
Author by
Jennifer Anthony
Updated on September 21, 2020Comments
-
Jennifer Anthony over 3 years
How can fix error
Message: Invalid argument supplied for foreach() - Line Number: 28
in followingforeach
?<?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); ?>
-
Niet the Dark Absol over 12 yearsTry
var_dump($mileage_input)
and see what you get. If you don't get an Array then it won't work. -
Marc B over 12 yearsThe
mileage' field must be named
mileage[]` in the html form, e.g.<input type="text" name="mileage[]" ...>
, otherwise PHP will NOT auto-convert it to an array in the _POST/_GET arrays. -
Félix Adriyel Gagnon-Grenier almost 9 yearspossible duplicate of Invalid argument supplied for foreach()
-
-
Matteo Riva over 12 yearsHiding the dust under the carpet won't make your house cleaner.
-
Alexander Olsson over 12 yearsVery 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.
-
Matteo Riva over 12 yearsIn 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).