Invalid argument supplied for foreach

0 votes

To handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_values();

foreach ($values as $value){
  ...
}

When you feed a foreach with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in [...]

 Can someone please help me with this error?

Apr 28, 2022 in Other DevOps Questions by Kichu
• 19,050 points
695 views

1 answer to this question.

0 votes

Use this:

if (is_array($values) || is_object($values))
{
    foreach ($values as $value)
    {
        ...
    }
}

This doesn't allocate an empty array when you've got nothing, to begin with anyway.

I hope this helps.

answered Apr 29, 2022 by narikkadan
• 63,680 points

Related Questions In Other DevOps Questions

0 votes
2 answers
0 votes
1 answer

how to check runtime for chef-client executions?

 Chef doesn't have the mechanism to save ...READ MORE

answered Jul 6, 2018 in Other DevOps Questions by DareDev
• 6,890 points
861 views
0 votes
1 answer
0 votes
0 answers

How to access mysql result set data with a foreach loop

I'm working on a PHP application that ...READ MORE

Jul 29, 2022 in PHP by Kithuzzz
• 38,020 points
2,879 views
0 votes
0 answers

PHP foreach loop key value

Running this DB call will provide me ...READ MORE

Aug 1, 2022 in PHP by Kithuzzz
• 38,020 points
1,649 views
0 votes
0 answers

How does PHP 'foreach' actually work?

Let me start by stating that I ...READ MORE

Aug 7, 2022 in PHP by Kithuzzz
• 38,020 points
919 views
+1 vote
2 answers

Scp Php files into server using gradle

Tru something like this: plugins { id ...READ MORE

answered Oct 11, 2018 in DevOps & Agile by lina
• 8,220 points
1,516 views
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP