Counting the length of strings in a program is an essential concept that helps in various coding scenarios. This can be done either by manually counting each character of the string one by one or using PHP's pre-defined function. In this tutorial, you will learn about the strlen() function of PHP.



Counting String Length Without Using the Predefined Function

Here is a code snippet that shows the basic approach of writing the logic of counting the string length is:

Example:

<?php
$strg = 'w3schools.in';
$g = 0;

while(@$strg[$g]) {
    $g++;
}

echo 'The length of ' . $strg . ' is: ' . $g . '.';
?>

Output:

The length of w3schools.in is: 12.

Or,

Example:

<?php

function strgleng($strg)
{
    $cnt = 0;
    for ($g = 0;$g < 1000;$g++)
    {
        if ($strg[$g] != "")
        {
            $cnt++;
        }
        else
        {
            break;
        }
    }
    return $cnt;
}
echo "The length of string is: ".strgleng("W3schools of Technology");
?>

Output:

The length of string is: 23.

The Concept of strlen() Function in PHP

PHP strlen() function is used to count the length of a given string or check the number of characters in a string. Here 'str' means string, and 'len' means length. It only takes one parameter, which is certainly imperative to implement this function. An integer value is returned when it becomes true.

The syntax of using this function is:

Syntax:

strlen(string $string) : int

An example of using this strlen() function is as follows:

Example:

<?php
    echo strlen('W3schools of Technology');
?>

This function will return the string's length (in bytes), shown in integer format whenever a successful execution is performed, or returns 0 when the string is empty. This function can be used in PHP 4.0 and above.

Use of the strlen() Function with Conditional Statements

Typically, this function is used to display the count of strings or is used with conditional statements. Here is a sample code snippet that shows the use of this function with the 'PHP if statement':

Example:

<?php

$cnt_strg = strlen('W3schools of Technology');

if ($get_string < 15)
{
    echo " The string length is less than 15.";
}
else
{
    echo "The length of the string is equal to or greater than 15.";
}

?>


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram