Php--warning:invalid argument supplied for foreach () in ...

Source: Internet
Author: User

1. Background

Today learn the use of Phpexcel in Code execution foreach ($data as $value) {...} A warning prompt appears:Warning: Invalid argument supplied for foreach () C3>35; Later, this warning means that the foreach () traversal of the output is an invalid array "Note that the invalid array is not equal to an empty array", and the cause of my error is that the correct code should be

"GetType ($i) This method, belongs to the database operation, I have all the database operations encapsulated into a method written in another file, there is no need to call the object, so the data is not taken to cause the array to be empty, resulting in $data this is an invalid array, resulting in an error! 】

2. Summary

In order to code in the official online operation frequently error:

We should make a judgment on the array variables before traversing: If the variable is not a valid array, setting the variable to an empty array is an array (), which is a good workaround! "Amount (⊙o⊙) ... But like me, careless, in the test is the first comment off the judgment, so as to know what is wrong! Because we have checked how to solve this warning, I hereby record that if there are other better methods or ideas, please correct me! 】

3. Workaround

"Here, I use the ternary operator to easily determine if an array is a valid array"

Is_array ($data = $db->gettype ($i))? Null: $data =array ();

This line of code means: To determine whether $data is a valid array, if the array is valid, continue the following operations, if the array is an invalid array, assign an empty array value to the $DATA variable

"Is_array (): Returns a Boolean value that determines whether the passed variable is a valid array! Note that an empty array $data =array () has a null value and is a valid array that you can test "

Php--warning:invalid argument supplied for foreach () in ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.