{"record":{"id":"b95a958c16458cc6","repo":"twigphp/Twig","slug":"the-random-function-cannot-pick-from-an-empty-sequence-or","errorCode":null,"errorMessage":"The \"random\" function cannot pick from an empty sequence or mapping.","messagePattern":"The \"random\" function cannot pick from an empty sequence or mapping\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/Extension/CoreExtension.php","lineNumber":516,"sourceCode":"            // unicode version of str_split()\n            // split at all positions, but not after the start and not before the end\n            $values = preg_split('/(?<!^)(?!$)/u', $values);\n\n            if ('UTF-8' !== $charset) {\n                foreach ($values as $i => $value) {\n                    $values[$i] = self::convertEncoding($value, $charset, 'UTF-8');\n                }\n            }\n        }\n\n        if (!is_iterable($values)) {\n            return $values;\n        }\n\n        $values = self::toArray($values);\n\n        if (0 === \\count($values)) {\n            throw new RuntimeError('The \"random\" function cannot pick from an empty sequence or mapping.');\n        }\n\n        return $values[array_rand($values, 1)];\n    }\n\n    /**\n     * Formats a date.\n     *\n     *   {{ post.published_at|date(\"m/d/Y\") }}\n     *\n     * @param \\DateTimeInterface|\\DateInterval|string|int|null $date     A date, a timestamp or null to use the current time\n     * @param string|null                                      $format   The target format, null to use the default\n     * @param \\DateTimeZone|string|false|null                  $timezone The target timezone, null to use the default, false to leave unchanged\n     */\n    public function formatDate($date, $format = null, $timezone = null): string\n    {\n        if (null === $format) {\n            $formats = $this->getDateFormat();","sourceCodeStart":498,"sourceCodeEnd":534,"githubUrl":"https://github.com/twigphp/Twig/blob/a414c3a491defb5a60f2fc88ef79ff37c90010cd/src/Extension/CoreExtension.php#L498-L534","documentation":"CoreExtension::random throws this Twig\\RuntimeError when the random() function is asked to pick from an empty sequence or mapping: after converting the argument via toArray(), count($values) is 0, so array_rand() would be meaningless and Twig rejects it up front.","triggerScenarios":"Calling {{ random(emptyArray) }} or twig_random($env, []) — any array/Traversable that toArray()-ed to zero items. (Note: random() with no argument or an integer/overloaded string input follows different branches and does not hit this check.)","commonSituations":"Picking a random ad/banner from a list that a DB query returned empty; random greeting from a config array not yet populated; null-to-empty coercion feeding random() in a template.","solutions":["Guarantee a non-empty collection before calling random(): {{ items|length ? random(items) : fallback }}.","Provide a default: {{ random(items|default(['default-item'])) }}.","If randomness over nothing is acceptable, use the no-argument form random() (picks a random number) instead of random([]).","Fix the data source so the array is populated before rendering."],"exampleFix":"// before (Twig)\n<img src=\"{{ random(banners) }}\">\n\n// after\n<img src=\"{{ banners|length ? random(banners) : 'default.png' }}\">","handlingStrategy":"type-guard","validationCode":"// guard before rendering with random($values)\nfunction pickRandom(array $values, $default = null) {\n    return $values !== [] ? $values[array_rand($values)] : $default;\n}","typeGuard":"function isNonEmptyCollection($v): bool { return (is_array($v) || $v instanceof \\Traversable) && count($v) > 0; }","tryCatchPattern":"try {\n    $html = $twig->render('banner.html.twig', ['banners' => $banners]);\n} catch (\\Twig\\Error\\RuntimeError $e) {\n    if (str_contains($e->getMessage(), '\"random\" function cannot pick from an empty sequence')) {\n        $html = $twig->render('banner.html.twig', ['banners' => ['default.png']]);\n    } else { throw $e; }\n}","preventionTips":["Use the |length check in templates: {{ items|length ? random(items) : fallback }}.","Provide sensible defaults via |default() for variables that may be empty arrays.","Validate data sources (DB queries, config arrays) return non-empty results before random selection.","Remember random() with no argument is safe; only random(emptyCollection) throws."],"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"}