strlen() Function in PHP 8.2, PHP 8.3 & PHP 8.4

The `strlen()` function in PHP returns the length of a given string. It’s a fundamental string operation that counts the number of bytes (not necessarily characters) in the string.Here’s how it works in PHP 8, PHP 8.1, PHP 8.2, PHP 8.3 and PHP 8.4.

Basic Syntax

<?php
strlen(string $string): int
?>

Example Usage in PHP 8.2

<?php
// Simple string
$text = "Hello, PHP 8.2!";
echo strlen($text); // Outputs: 14

// Empty string
$empty = "";
echo strlen($empty); // Outputs: 0

// String with special characters
$special = "Café";
echo strlen($special); // Outputs: 5 (é takes 2 bytes in UTF-8)

// Multibyte string (for character count, use mb_strlen())
$multibyte = "こんにちは";
echo strlen($multibyte); // Outputs: 15 (each Japanese character takes 3 bytes)
echo mb_strlen($multibyte, 'UTF-8'); // Outputs: 5 (correct character count)
?>

Important Notes for PHP 8.2

1. `strlen()` counts bytes, not characters. For multibyte strings (like UTF-8), use `mb_strlen()` instead.

2. In PHP 8.2, there are no significant changes to `strlen()` compared to previous versions.

3. The function will return 0 for:
– Empty strings
– Strings containing only the NULL byte (“\0”)
– Variables set to false

4. For non-string values, PHP will attempt to convert them to strings first.