Core\Bytes::length
Core\Bytes::length(bytes $b): uintCore\Bytes::length( bytes $b, ): uint
Counts the bytes in a bytes value.
The result is the number of bytes. For a value with nothing in it the result is 0. This is not the number of characters. A text written in UTF-8 uses one byte for a and two bytes for é. Counting the bytes of such a text gives a larger number than counting its characters. Use Core\Str::length when you want the characters a person sees.
Counting is immediate. The size is stored with the value, so the method does not read the bytes. A value of one hundred megabytes is counted as fast as a value of ten bytes.
Good to know: a size limit on an upload, a request body or a stored value is a limit on bytes. This is the method those checks use.
Parameters
$bbytesThe buffer to measure.
Return value
Returns uint. The number of bytes. It is 0 for an empty buffer.
Examples
Counting the bytes of a value
<?nvs// Shows how to count the bytes of a value. `Core\Bytes::length` returns the// size of the value in bytes.
// There is no way to write bytes directly in a program, so this converts text.bytes $data = 'Hi!' as bytes;
// The value has 3 bytes, so this prints 3.echo Core\Bytes::length($data), "\n";
// A value with nothing in it has 0 bytes.echo Core\Bytes::length('' as bytes), "\n";30Bytes are not characters
<?nvs// Shows the difference between bytes and characters. The text here is written// in UTF-8, where some letters need more than one byte.
string $word = 'Größe';
// `Core\Str::length` counts what a person sees. This prints 5.echo Core\Str::length($word), "\n";
// "ö" and "ß" need two bytes each, so the text is 7 bytes. This prints 7.echo Core\Bytes::length($word as bytes), "\n";57Checking an upload against a size limit
<?nvs// Shows how a program checks the size of an uploaded file. A size limit counts// bytes, so this is the check that reads `Core\Bytes::length`.
final class Upload{ // Returns true when the file is small enough to store. public static function fits(bytes $file, uint $limit): bool { return Core\Bytes::length($file) <= $limit; }}
// Two files of 2048 and 1048576 bytes, both filled with the letter "A".bytes $small = Core\Bytes::fill(2048, 65);bytes $large = Core\Bytes::fill(1048576, 65);
// The limit is 65536 bytes. The small file is under it, so this prints "yes".echo Upload::fits($small, 65536) ? 'yes' : 'no', "\n";
// The large file is over the limit, so this prints "no".echo Upload::fits($large, 65536) ? 'yes' : 'no', "\n";yesno