I have this code for my school project and thought the code does its job on what i wanted it to do, i still keep on getting the error about $_SESSION[] is not an array argument when using the array_replace()
and array_merge()
functions:
Session is already initiated on the header:
// Start Session
session_start();
For initialising the $_SESSION['cart']
as an array:
// Parent array of all items, initialized if not already...
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
For adding products from a dropdown menu: - (Just to see how the session is assigned:)
if (isset($_POST['new_item'])) { // If user submitted a product
$name = $_POST['products']; // product value is set to $name
// Validate adding products:
if ($name == 'Select a product') { // Check if default - No product selected
$order_error = '<div class="center"><label class="error">Please select a product</label></div>';
} elseif (in_array_find($name, $_SESSION['cart']) == true) { // Check if product is already in cart:
$order_error = '<div class="center"><label class="error">This item has already been added!</label></div>';
} else {
// Put values into session:
// Default quantity = 1:
$_SESSION['cart'][$name] = array('quantity' => 1);
}
}
Then here is where the issue comes, when they try to update the product:
// for updating product quantity:
if(isset($_POST['update'])) {
// identify which product to update:
$to_update = $_POST['hidden'];
// check if product array exist:
if (in_array_find($to_update, $_SESSION['cart'])) {
// Replace/Update the values:
// ['cart'] is the session name
// ['$to_update'] is the name of the product
// [0] represesents quantity
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
// Alternatively use array merge for php < 5.3
// array_merge($replacement, $base);
}
}
Note that both the functions array_replace()
and array_merge()
are updating the values and doing what the initial goal was, but the problem is that i still keep on getting that one argument($base
) is not an array issue.
Warning: array_replace() [function.array-replace]: Argument #1 is not an array in ...
any suggestions for a better way to approach this issue would be a valuable help :) Thanks for your help :)
Edit: The in_array_find()
is a function that i use in replacement of in_array()
as it doesn't apply to finding values in a multi-dimensional array: specifically 2 depth arrays:
found it from here and it works for me
The code for it is:
// Function for searching values inside a multi array:
function in_array_find($needle, $haystack, $strict = false) {
foreach ($haystack as $item => $arr) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}