{"record":{"id":"adf8e9ebe6805144","repo":"twigphp/Twig","slug":"the-cycle-function-expects-a-non-empty-sequence","errorCode":null,"errorMessage":"The \"cycle\" function expects a non-empty sequence.","messagePattern":"The \"cycle\" function expects a non-empty sequence\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/Extension/CoreExtension.php","lineNumber":446,"sourceCode":"    public static function cycle($values, $position): mixed\n    {\n        if (!\\is_array($values)) {\n            if (!$values instanceof \\ArrayAccess) {\n                throw new RuntimeError('The \"cycle\" function expects an array or \"ArrayAccess\" as first argument.');\n            }\n\n            if (!is_countable($values)) {\n                // To be uncommented in 4.0\n                // throw new RuntimeError('The \"cycle\" function expects a countable sequence as first argument.');\n\n                trigger_deprecation('twig/twig', '3.12', 'Passing a non-countable sequence of values to \"%s()\" is deprecated.', __METHOD__);\n\n                $values = self::toArray($values, false);\n            }\n        }\n\n        if (!$count = \\count($values)) {\n            throw new RuntimeError('The \"cycle\" function expects a non-empty sequence.');\n        }\n\n        return $values[$position % $count];\n    }\n\n    /**\n     * Returns a random value depending on the supplied parameter type:\n     * - a random item from a \\Traversable or array\n     * - a random character from a string\n     * - a random integer between 0 and the integer parameter.\n     *\n     * @param \\Traversable|array|int|float|string $values The values to pick a random item from\n     * @param int|null                            $max    Maximum value used when $values is an int\n     *\n     * @return mixed A random value from the given sequence\n     *\n     * @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is)\n     *","sourceCodeStart":428,"sourceCodeEnd":464,"githubUrl":"https://github.com/twigphp/Twig/blob/a414c3a491defb5a60f2fc88ef79ff37c90010cd/src/Extension/CoreExtension.php#L428-L464","documentation":"CoreExtension::cycle throws this Twig\\RuntimeError when the cycle() function receives an empty sequence (array/Traversable that toArray()-ed to 0 items). cycle($values, $position) needs at least one element to index into, so count($values) === 0 is rejected before computing $values[$position % $count].","triggerScenarios":"Calling {{ cycle(rows, loop.index0) }} or twig_cycle($values, $i) where $values is [] (or an empty Traversable, or a scalar that is not a string and toArray()'s to nothing), regardless of the position argument.","commonSituations":"Alternating row colors on a table whose data array is empty because a query returned no rows; passing a nullable variable that defaults to [] instead of the intended pair ['odd','even']; passing null (after toArray coercion) to cycle inside a loop.","solutions":["Ensure the sequence passed to cycle has at least one element; provide defaults, e.g. cycle(values|default(['a','b']), i).","Guard the loop: only call cycle when the collection is non-empty (or rely on a for loop that skips empty sets).","If the value may be null, coalesce first: cycle(someArray ?? ['odd','even'], loop.index0).","Check upstream data-fetching logic that unexpectedly yields an empty array."],"exampleFix":"// before (Twig)\n<tr class=\"{{ cycle(['odd', 'even'], loop.index0) }}\">\n\n// after\n<tr class=\"{{ cycle(colors|default(['odd', 'even']), loop.index0) }}\">","handlingStrategy":"type-guard","validationCode":"// PHP caller-side guard before rendering with cycle()\nfunction safeCycle(array $values, int $position, array $fallback = ['odd', 'even']): string {\n    return $values !== [] ? $values[$position % count($values)] : $fallback[$position % count($fallback)];\n}","typeGuard":"function isNonEmptyList($v): bool { return is_array($v) && $v !== []; }","tryCatchPattern":"try {\n    $html = $twig->render('table.html.twig', ['rows' => $rows]);\n} catch (\\Twig\\Error\\RuntimeError $e) {\n    if (str_contains($e->getMessage(), '\"cycle\" function expects a non-empty sequence')) {\n        $html = $twig->render('table.html.twig', ['rows' => $rows, 'colors' => ['odd', 'even']]);\n    } else { throw $e; }\n}","preventionTips":["Never pass raw query results to cycle(); pipe through |default(['a','b']).","Prefer using loop.index-based CSS like {{ loop.index is odd ? 'odd' : 'even' }} which cannot fail on empty arrays.","Check collections for emptiness before looping/striping rows.","Coerce nullable variables with ?? before passing to cycle()."],"tags":["twig","runtime-error","empty-array"],"backgroundTag":"empty-required-field","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"}