'php Fatal error: Cannot use positional argument after named argument
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;
}
}
}
Solution 1:[1]
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
implodeshows the arguments as namedseparatorandarray, soglueis not a valid name. (The manual used to call themglueandpieces, 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: ',');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
