dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

strnatcasecmp> <stristr
[edit] Last updated: Fri, 28 Jun 2013

view this page in

strlen

(PHP 4, PHP 5)

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

  • count() - Count all elements in an array, or something in an object
  • mb_strlen() - Get string length



strnatcasecmp> <stristr
[edit] Last updated: Fri, 28 Jun 2013
 
add a note add a note User Contributed Notes strlen - [11 notes]
up
24
tux at tax dot tox
10 months ago
Attention with utf8:
$foo = "bär";
strlen($foo) will return 4 and not 3 as expected..
up
8
vcardillo at gmail dot com
10 months 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.
up
10
chernyshevsky at hotmail dot com
8 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.
up
4
Amaroq
4 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.
up
3
packe100 at hotmail dot com
8 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.
up
1
bartek at proteus,pl
7 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
up
0
basil at gohar dot us
3 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.
up
0
http://nsk.wikinerds.org
8 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.
up
-1
topera at gmail dot com
6 years ago
<?php
//------------------------------------------
// This function returns the necessary
// size to show some string in display
// For example:
// $a = strlen_layout("WWW"); // 49
// $a = strlen_layout("..."); // 16
// $a = strlen_layout("Hello World"); // 99
//------------------------------------------
function strlen_pixels($text) {
   
/*
        Pixels utilized by each char (Verdana, 10px, non-bold)
        04: j
        05: I\il,-./:; <espace>
        06: J[]f()
        07: t
        08: _rz*
        09: ?csvxy
        10: Saeko0123456789$
        11: FKLPTXYZbdghnpqu
        12: AÇBCERV
        13: <=DGHNOQU^+
        14: w
        15: m
        16: @MW
    */

    // CREATING ARRAY $ps ('pixel size')
    // Note 1: each key of array $ps is the ascii code of the char.
    // Note 2: using $ps as GLOBAL can be a good idea, increase speed
    // keys:    ascii-code
    // values:  pixel size

    // $t: array of arrays, temporary
   
$t[] = array_combine(array(106), array_fill(0, 1, 4));

   
$t[] = array_combine(array(73,92,105,108,44), array_fill(0, 5, 5));
   
$t[] = array_combine(array(45,46,47,58,59,32), array_fill(0, 6, 5));
   
$t[] = array_combine(array(74,91,93,102,40,41), array_fill(0, 6, 6));
   
$t[] = array_combine(array(116), array_fill(0, 1, 7));
   
$t[] = array_combine(array(95,114,122,42), array_fill(0, 4, 8));
   
$t[] = array_combine(array(63,99,115,118,120,121), array_fill(0, 6, 9));
   
$t[] = array_combine(array(83,97,101,107), array_fill(0, 4, 10));
   
$t[] = array_combine(array(111,48,49,50), array_fill(0, 4, 10));
   
$t[] = array_combine(array(51,52,53,54,55,56,57,36), array_fill(0, 8, 10));
   
$t[] = array_combine(array(70,75,76,80), array_fill(0, 4, 11));
   
$t[] = array_combine(array(84,88,89,90,98), array_fill(0, 5, 11));
   
$t[] = array_combine(array(100,103,104), array_fill(0, 3, 11));
   
$t[] = array_combine(array(110,112,113,117), array_fill(0, 4, 11));
   
$t[] = array_combine(array(65,195,135,66), array_fill(0, 4, 12));
   
$t[] = array_combine(array(67,69,82,86), array_fill(0, 4, 12));
   
$t[] = array_combine(array(78,79,81,85,94,43), array_fill(0, 6, 13));
   
$t[] = array_combine(array(60,61,68,71,72), array_fill(0, 5, 13));
   
$t[] = array_combine(array(119), array_fill(0, 1, 14));
   
$t[] = array_combine(array(109), array_fill(0, 1, 15));
   
$t[] = array_combine(array(64,77,87), array_fill(0, 3, 16));  
  
   
// merge all temp arrays into $ps
   
$ps = array();
    foreach(
$t as $sub) $ps = $ps + $sub;
  
   
// USING ARRAY $ps
   
$total = 1;
    for(
$i=0; $i<strlen($text); $i++) {
       
$temp = $ps[ord($text[$i])];
        if (!
$temp) $temp = 10.5; // default size for 10px
       
$total += $temp;
    }
    return
$total;
}
?>

Rafael Pereira dos Santos
up
0
jasonrohrer at fastmail dot fm
18 days 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).
up
-7
bradmwalker at cableone dot net
6 years ago
want a predicate that tests a string for emptiness? use strlen instead of empty(). strlen only returns a false-equivalent value for ''.

example:

<?php
// takes string_array and returns an array without any values w/empty strings
function filter_empties ($string_array) {
   
// note: the immensely retarded empty() function returns true on string '0'
    // use strlen as empty string predicate
   
return count($string_array) ? array_filter ($string_array, 'strlen') : $string_array;
}
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites