ValueError
PHPERRORCommonValidation

Argument has the right type but an invalid value

Quick Answer

Validate inputs before calling built-in functions that throw ValueError for out-of-range values.

What this means

Thrown (PHP 8.0+) when an argument is the correct type but its value is not valid for the function — e.g., array_chunk with size < 1.

Why it happens
  1. 1array_chunk($arr, 0) — chunk size must be >= 1
  2. 2str_repeat with negative count

Fix

Validate before calling

Validate before calling
$size = max(1, (int) $input);
$chunks = array_chunk($array, $size);

Why this works

Clamping the value to a valid range prevents ValueError before the call.

Code examples
Triggerphp
array_chunk([1,2,3], 0); // ValueError: array_chunk(): Argument #2 must be greater than 0
Catchphp
try {
    $r = array_chunk($arr, $n);
} catch (ValueError $e) {
    $r = [$arr]; // fallback: one chunk
}

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PHP errors