Andrew Smith
Andrew Smith

Reputation: 310

PHP Merging and printing two arrays

I posted this question a little earlier, but here is the full version.

I am trying to merge two arrays. The Eating Array (which has nothing in it at present) and the Dairy Array (because the user ticked yes to Dairy on a separate html page).

However, when I combine these two, into a new array ($newArray) all that happens is the following error:

 Warning: Invalid argument supplied for foreach() in
           /home/****/****/website.php on line 65

Line 65 is identified in the comments.

<?php 

 $EatingArray=array();

 echo "<p>";


 $DrinksArray = array(
     'a' => 'Coca Cola',
     'b' => 'Fanta',
 'c' => 'Sprite',
);
 $FoodArray = array(
     'd' => 'Hamburger',
     'e' => 'Pie',
 'f' => 'Chips',
);
 $SweetsArray = array(
     'g' => 'Musk Sticks',
     'h' => 'Maltesers',
 'i' => 'M&Ms',
);
 $DairyArray = array(
     'j' => 'Milk',
     'k' => 'Yoghurt',
 'l' => 'Cheese',
);


if ($_POST['DairyCheckBox'] == 'yes')
 {
 $newArray = array_merge($EatingArray, $DairyArray);
 }
foreach ($newArray as $key => $value)    //LINE 65

{
        echo $value;
}



 echo "<p>";
 ?>

Thanks for you help in advance.

Andrew

Upvotes: 1

Views: 81

Answers (1)

Bora
Bora

Reputation: 10717

You should move into if clause your foreach

Your array_merge is inside ifclause with checking$_POST. You're tryingforeachbeforePOST` and getting error

if ($_POST['DairyCheckBox'] == 'yes')
{
    $newArray = array_merge($EatingArray, $DairyArray);

    foreach ($newArray as $key => $value)    //LINE 65
    {
            echo $value;
    }
}

Upvotes: 2

Related Questions