How to Get PHP String Length

Minahil Noor Feb 02, 2024
  1. Use the strlen() Function to Measure String Length in Bytes in PHP
  2. Use the mb_strlen() Function to Measure String Length in Bytes in PHP
How to Get PHP String Length

This article will introduce different methods to get the PHP string size in bytes.

Use the strlen() Function to Measure String Length in Bytes in PHP

We will use PHP’s built-in function strlen() to get the string length in bytes. It is a specialized function for finding string length. The correct syntax to use this function is as follows.

strlen($string);

This function has one parameter only. The detail of its parameter is as follows.

Variables Description
$string It is the string whose length will be returned by the function.

This function returns the length of the string. The program below shows how we can use the strlen() function to measure the length of a PHP string in bytes.

<?php
$mystring = "This is my string";
echo("The string length in bytes is: ");
echo(strlen($mystring));
?>

Output:

The string length in bytes is: 17

The function has returned the string length in bytes.

Use the mb_strlen() Function to Measure String Length in Bytes in PHP

We can also use the mb_strlen() function to get the string length in bytes. But it is less efficient than strlen() function. The correct syntax to use this function is as follows.

mb_strlen($string, $encoding);

This function has two parameters. The detail of its parameter is as follows.

Variables Description
$string It is the string whose length will be returned by the function.
$encoding It is the encoding we have used for our string because different encoding schemes have different sizes.

This function returns the length of the string. The program below shows how we can use the mb_strlen() function to get the PHP string length.

<?php
$mystring = "This is my string";
echo("The string length in bytes is: ");
echo(mb_strlen($mystring));
?>

Output:

The string length in bytes is: 17

The function has returned the measured string length in bytes.

Related Article - PHP String