PHP 7.0.6 Released

strlen

(PHP 4, PHP 5, PHP 7)

strlenGet string length

Description

int strlen ( string $string )

Returns the length of the given string.

Parameters

string

The string being measured for length.

Return Values

The length of the string on success, and 0 if the string is empty.

Changelog

Version Description
5.3.0 Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

Examples

Example #1 A strlen() example

<?php
$str 
'abcdef';
echo 
strlen($str); // 6

$str ' ab cd ';
echo 
strlen($str); // 7
?>

Notes

Note:

strlen() returns the number of bytes rather than the number of characters in a string.

Note:

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

See Also

User Contributed Notes

chernyshevsky at hotmail dot com
11 years ago
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

<?php
$length
= strlen(utf8_decode($s));
?>

utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.
rm dot nasir at hotmail dot com
4 months ago
I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().

Example:

<?php
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = "السلام علیکم ورحمة الله وبرکاته!";

var_export( strlen($utf8) ); // 59
echo "<br>";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>
vcardillo at gmail dot com
3 years ago
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?

<?php
$foo
= null;
$len = strlen(null);
$bar = '';

echo
"Length: " . strlen($foo) . "<br>";
echo
"Length: $len <br>";
echo
"Length: " . strlen(null) . "<br>";

if (
strlen($foo) === 0) echo 'Null length is Zero <br>';
if (
$len === 0) echo 'Null length is still Zero <br>';

if (
strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (
strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';

if (
strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (
strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';
?>

// Begin Output:
Length: 0
Length: 0
Length: 0

Null length is Zero
Null length is still Zero

!is_null(): $foo is probably null
isset(): $foo is probably null

!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output

So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
tux at tax dot tox
3 years ago
Attention with utf8:
$foo = "bär";
strlen($foo) will return 4 and not 3 as expected..
basil at gohar dot us
5 years ago
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes
= array('one', 'two', 'three');

if (
strlen($attributes) == 0 && !is_bool($attributes)) {
    echo
"We are in the 'if'\n"//  PHP 5.3
} else {
    echo
"We are in the 'else'\n"//  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.
jasonrohrer at fastmail dot fm
2 years ago
PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0'). 

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

For example, in PHP:

strlen( "te\0st" ) = 5

In C, the same call would return 2.

Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
vaqasuddin
1 year ago
function limit_text( $text, $limit = 100000000000 ) {
        if ( strlen ( $text ) < $limit ) {
            return $text;
        }
        $split_words = explode(' ', $text );
        $out = null;
        foreach ( $split_words as $word ) {
            if ( ( strlen( $word ) > $limit ) && $out == null ) {
                return substr( $word, 0, $limit )."...";
            }
           
            if (( strlen( $out ) + strlen( $word ) ) > $limit) {
                return $out . "...";
            }           
            $out.=" " . $word;
        }
        return $out;
    }

echo limit_text("hello world lorem ipsum",10);
http://nsk.wikinerds.org
11 years ago
Beware: strlen() counts new line characters at the end of a string, too!

<?php
  $a
= "123\n";
  echo
"<p>".strlen($a)."</p>";
?>

The above code will output 4.
bartek at proteus,pl
10 years ago
> Just a precisation, maybe obvious, about the strlen() behaviour:
> with binary strings (i.e. returned by the pack() finction) is made
> a byte count... so strlen returns the number of bytes contained
> in the binary string.

This is not always true. strlen() might be shadowed by mb_strlen().
If that is the case it might treat binary data as unocode string and return wrong value (I just found it out after fighting with egroupware email attachment handling bug).

So, if your data is binary I would suggest using somthing like this (parts of the code from egroupware):

<?php
$has_mbstring
= extension_loaded('mbstring') ||@dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX);
$has_mb_shadow = (int) ini_get('mbstring.func_overload');

if (
$has_mbstring && ($has_mb_shadow & 2) ) {
  
$size = mb_strlen($this->output_data,'latin1');
} else {
  
$size = strlen($this->output_data);
}
?>
--
Bartek
Amaroq
7 years ago
When dealing with submitted forms that you've imposed a character limit on, you must remember that functions that count characters consider "\r\n" to be two characters.

<?php
//These will both output 2.
echo strlen("\r\n");
echo
mb_strlen("\r\n");
?>

If I had thought of this starting out, I would have saved myself several hours of trouble trying to get php to cut a message to the same length that my auxiliary javascript validation imposed on it.
MD ABU SAYEM
2 years ago
Simple code for palindrome
<?PHP
$str
='racecar';
echo
$str.'   ';
$len=strlen($str)-1;
$new='';
for(
$i=$len;$i>=0;$i--){
$new.=$str[$i];
}
echo
$new;
?>
packe100 at hotmail dot com
11 years ago
Just a precisation, maybe obvious, about the strlen() behaviour: with binary strings (i.e. returned by the pack() finction) is made a byte count... so strlen returns the number of bytes contained in the binary string.
johan at hultin dot se
1 month ago
I've found this quite peculiar error (I think it might be truncating something, but not sure why and where that occurs)

The string is the amount of unique shuffles of a deck of cards, and in it's raw form it's this 80658175170943878571660636856403766975289505440883277824000000000000

if you however use strlen() to count this, it will return 19, which clearly the string is longer than
To Top