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 {
Share:
27,143
Jennifer Anthony
Author by

Jennifer Anthony

Updated on September 21, 2020

Comments

  • Jennifer Anthony
    Jennifer Anthony over 3 years

    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);
    ?>
    
    • Niet the Dark Absol
      Niet the Dark Absol over 12 years
      Try var_dump($mileage_input) and see what you get. If you don't get an Array then it won't work.
    • Marc B
      Marc B over 12 years
      The 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
      Félix Adriyel Gagnon-Grenier almost 9 years
  • Matteo Riva
    Matteo Riva over 12 years
    Hiding the dust under the carpet won't make your house cleaner.
  • Alexander Olsson
    Alexander Olsson over 12 years
    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.
  • Matteo Riva
    Matteo Riva over 12 years
    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).