PHP中array_push报错:参数1应为数组却为null的解决咨询
array_push() Null Warning in Your PHP Code Let's break down this issue step by step. The error message Warning: array_push() expects parameter 1 to be array, null given points to one of your array_push() calls receiving a null instead of an array. While you've been troubleshooting $errorsarray, the most likely culprit here is $_SESSION["shoppingcart"]—let me explain why:
Why the Error Happens
Looking at your code, when $continue is true, you loop through $_SESSION["advanced_builder"] and try to push items into $_SESSION["shoppingcart"]:
foreach ($_SESSION["advanced_builder"] as $product) { array_push($_SESSION["shoppingcart"], $product); }
If $_SESSION["shoppingcart"] was never initialized (i.e., this is the first time a user adds items to their cart), it will be null by default. array_push() can't operate on null, hence the warning.
How to Fix It
You have two simple, reliable ways to resolve this:
1. Initialize the Session Array Before Using It
Add a check right before your foreach loop to ensure $_SESSION["shoppingcart"] is an array. If it doesn't exist or isn't an array, initialize it:
if ($continue) { echo "<div class='row' style='text-align: center; margin-top: 5%;'> <div class='col-12'> <h3 style='color: green'>Systeem volledig compatibel! De correcte producten zijn aan uw winkelmand toegevoegd.</h3> </div> </div>"; // Initialize shopping cart if it doesn't exist if (!isset($_SESSION["shoppingcart"]) || !is_array($_SESSION["shoppingcart"])) { $_SESSION["shoppingcart"] = []; } foreach ($_SESSION["advanced_builder"] as $product) { array_push($_SESSION["shoppingcart"], $product); } }
2. Use PHP's Array Append Syntax (Simpler & Safer)
Instead of array_push(), use the shorthand [] syntax to append items. This automatically initializes the array if it doesn't exist:
foreach ($_SESSION["advanced_builder"] as $product) { $_SESSION["shoppingcart"][] = $product; }
This is my preferred approach—it's more concise and avoids the need for explicit initialization checks.
Verifying $errorsarray
For completeness, let's confirm $errorsarray isn't the issue: you initialize it at the top of the isset($_POST['getAdvancedResults']) block with $errorsarray = array();, so any array_push() calls on it later in that block will work as expected. The only way this would fail is if there's code outside what you've shared that overwrites $errorsarray to null, but based on your snippet, that's not happening.
内容的提问来源于stack exchange,提问作者Ino van den Berg

