I am creating a cart for an e-commerce website. Here I am trying to insert the product ID and the user ID to the cart table in my database. I'm guessing I'm not using the impolde correctly.
public function inserIntoCart($para = null, $table = "cart")
{
if($this->db->con != null){
if($para != null){
$columns = implode(glue: ',', array_keys($para));
$values = implode(glue: ',', array_values($para));
$query_string = sprintf(format: "INSERT INTO %s(%s) VALUES (%s)", $table, $columns, $values);
$result = $this->db->query($query_string);
return $result;
}
}
}
CodePudding user response:
Your problem is not with implode
as such, but with how to use named arguments.
As of PHP 8.0, you can use the name: $value
syntax to pass named arguments in any order, but you need to follow certain rules:
- The names for the arguments must match the function definition
- If you mix named arguments with positional arguments (normal arguments with no
name:
before them), the positional ones have to come first
In this case:
- The manual page for
implode
shows the arguments as namedseparator
andarray
, soglue
is not a valid name. (The manual used to call themglue
andpieces
, but this was updated to match the names in the 8.0 implementation in Jan 2021.) - You've given a name for your first argument, but not your second (which is what your error message says).
So the following would all be acceptable:
// Normal positional arguments
$columns = implode(',', array_keys($para));
// Positional first argument, named second argument
$columns = implode(',', array: array_keys($para));
// Name both arguments, in either order
$columns = implode(separator: ',', array: array_keys($para));
$columns = implode(array: array_keys($para), separator: ',');