{"record":{"id":"8a07355a5746cb3b","repo":"twigphp/Twig","slug":"when-using-set-you-must-have-the-same-number-of-variables","errorCode":null,"errorMessage":"When using set, you must have the same number of variables and assignments.","messagePattern":"When using set, you must have the same number of variables and assignments\\.","errorType":"exception","errorClass":"SyntaxError","httpStatus":null,"severity":"error","filePath":"src/TokenParser/SetTokenParser.php","lineNumber":47,"sourceCode":" *\n * @internal\n */\nfinal class SetTokenParser extends AbstractTokenParser\n{\n    public function parse(Token $token): Node\n    {\n        $lineno = $token->getLine();\n        $stream = $this->parser->getStream();\n        $names = $this->parseAssignmentExpression();\n\n        $capture = false;\n        if ($stream->nextIf(Token::OPERATOR_TYPE, '=')) {\n            $values = $this->parseMultitargetExpression();\n\n            $stream->expect(Token::BLOCK_END_TYPE);\n\n            if (\\count($names) !== \\count($values)) {\n                throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext());\n            }\n        } else {\n            $capture = true;\n\n            if (\\count($names) > 1) {\n                throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext());\n            }\n\n            $stream->expect(Token::BLOCK_END_TYPE);\n\n            $values = $this->parser->subparse([$this, 'decideBlockEnd'], true);\n            $stream->expect(Token::BLOCK_END_TYPE);\n        }\n\n        return new SetNode($capture, $names, $values, $lineno);\n    }\n\n    public function decideBlockEnd(Token $token): bool","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/twigphp/Twig/blob/a414c3a491defb5a60f2fc88ef79ff37c90010cd/src/TokenParser/SetTokenParser.php#L29-L65","documentation":"A compile-time SyntaxError raised in SetTokenParser::parse: this is a generic arity-validation guard inside the parser. When a {% set %} tag assigns to multiple targets (e.g. {% set a, b = ... %}), the parser checks that the number of assignment targets equals the number of value expressions; the error fires when a template author writes mismatched counts, such as two variables but only one value expression, so Twig cannot pair each variable with its value.","triggerScenarios":"Writing '{% set a, b = [1] %}' (2 targets, 1 value) or '{% set a = 1, 2 %}' (1 target, 2 values); parse throws after comparing count($names) with count($values).","commonSituations":"Refactoring a set to add or remove a variable without updating the right-hand side; assuming array elements spread across multiple targets automatically.","solutions":["Make the target list and value list the same length, e.g. '{% set a, b = 1, 2 %}'","Assign a single array to one variable and index it afterwards if counts differ","Use capture syntax ({% set a %}...{% endset %}) only for single targets"],"exampleFix":"// before\n{% set firstName, lastName = user.fullName %}\n// after\n{% set firstName, lastName = user.firstName, user.lastName %}","handlingStrategy":"validation","validationCode":"// Count targets vs values in set-with-= statements\nif (preg_match('/\\{%\\s*set\\s+([^=}%]+)\\s*=\\s*(.+?)\\s*%}/', $src, $m)) {\n    $targets = count(array_map('trim', explode(',', $m[1])));\n    $values  = preg_match_all('/(?<![|\\w])(?:[\\'\\\"].*?[\\'\\\"]|\\w+(?:\\([^)]*\\))?)/', $m[2]);\n    if ($targets !== $values) {\n        throw new InvalidArgumentException('set targets and values must match in count.');\n    }\n}","typeGuard":null,"tryCatchPattern":"try {\n    $twig->render($template, $ctx);\n} catch (SyntaxError $e) {\n    if (str_contains($e->getMessage(), 'same number of variables and assignments')) {\n        // surface authoring error back to template editor\n    }\n    throw $e;\n}","preventionTips":["Whenever you add/remove a variable in a multi-set, update the right-hand side in the same commit","Prefer single-variable sets and destructuring via |split or array destructuring patterns","Lint templates before deployment"],"tags":["twig","set","syntax-error","template"],"backgroundTag":"invalid-argument-value","analyzedSha":"a414c3a491defb5a60f2fc88ef79ff37c90010cd","analyzedAt":"2026-09-13T15:10:46.849Z","contentChangedAt":"2026-09-13T15:10:46.849Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}