Home > Mobile >  php Fatal error: Cannot use positional argument after named argument
php Fatal error: Cannot use positional argument after named argument

Time:04-06

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:

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: ',');
  • Related