-1

I am trying to solve a Invalid argument supplied for foreach() warning. I am 99% certain that this is related to the version of PHP running on our server, but for the moment that can't be changed, so I am looking to "fix" the code instead.

The code snippet:

$array = $this->cal;
$events = $array['VEVENT'];
foreach ($array['VEVENT'] as $anEvent) {

I am getting the Invalid warning on the foreach statement. It works fine on a PHP 5.4 server, but when moved to a 5.3 server, I have the problem. How can I "downgrade" the code? I have been beating my head against the screen digging through all the different comments, but can't figure out the solution. The code was provided by a sub-contracted developer who is now unreachable, so...

Appreciate the help and education...

hakre
  • 193,403
  • 52
  • 435
  • 836
Kaleb
  • 17
  • 5
  • 1
    `$array['VEVENT']` is array? can you post `var_dump` $array ? – waki Dec 21 '14 at 15:32
  • possible duplicate of [Invalid argument supplied for foreach()](http://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – hakre Mar 20 '15 at 12:06

3 Answers3

1

The code snippet you provided will fail whether it's PHP 5.3 or 5.4 because the $array['VEVENT'] does not appear to be an array. You may want to look at the code that generates the cal property of your object. In the mean time, you can resolve the error by checking if $array['VEVENT'] is an array or not.

$array = $this->cal;
$events = $array['VEVENT'];
if(isset($array['VEVENT"] && is_array($array['VEVENT'])) {
  foreach ($array['VEVENT'] as $anEvent) {
     // do stuff with $anEvent
  }
}
Robbert
  • 6,481
  • 5
  • 35
  • 61
  • Your answer is the most accurate to what was causing the problem. It turns out that the file it was reading was using some invalid characters, therefore creating a problem with the array. The actual code however was 5.3 compliant, so I have learned. – Kaleb Dec 21 '14 at 20:50
-1

fputcsv($handle, array('','','Ticket_Detail'));

fputcsv($handle, array(''));

foreach($results as $row) { fputcsv($handle, array('Ticket No:'.$row['Ticketno']));

 $ticketno1=$row['Ticketno'];

fputcsv($handle, array(''));
-2

It's probably happening because the array is empty.

$array = $this->cal;
$events = $array['VEVENT'];
if ( ( is_array ( $array['VEVENT'] ) ) && ( !empty ( $array['VEVENT'] ) ) ) {
    foreach ($array['VEVENT'] as $anEvent) {
    }
} else {
    echo 'empty or not an array';
}
Duniyadnd
  • 4,013
  • 1
  • 22
  • 29
  • Just because a variable isn't empty doesn't make it an array. The above code would still fail for something like `$array['VEVENT'] = 5` – Robbert Dec 21 '14 at 15:51
  • You're right, I made an assumption that the OP knows that the output is an array. I guess I should check the meta to see how far can these sorts of assumptions go. – Duniyadnd Dec 21 '14 at 15:54
  • Easy fix, change `!empty($array['VEVENT'])` to `is_array($array['VEVENT'])` – Robbert Dec 21 '14 at 15:56