Counting the length of a string in a program is an essential concept that is used in various coding scenarios. This can be done either by manually typing the entire looping program to count each character of the string, or using a pre-defined function of PHP. In this tutorial, you will learn about the strlen() function of PHP.



Counting the Length of a String Using Loops

Here is a code snippet that shows the basic approach of writing logic to count string length using "while loop":

Example:

<?php
$String = 'w3schools.in';
$i = 0;
while($String[$i]) {
    $i++;
}
echo "The length of $String is: " . $i . ".";
?>

Output:

The length of w3schools.in is: 12.

Here is another code snippet that shows the approach of writing logic to count string length using "for loop":

Example:

<?php

function strlength($Str)
{
    $length= 0;
    for ($i = 0; $i < 1000; $i++)
    {
        if ($Str[$i] != "")
        {
            $length++;
        }
        else
        {
            break;
        }
    }
    return $length;
}

$Str = "Rasmus Lerdorf";
echo "The length of $Str is: " . strlength($Str). ".";

?>

Output:

The length of Rasmus Lerdorf is: 14.

Counting the Length of a String Using strlen() Function

To count the length of a given string or to check the number of characters in a string, the PHP strlen() function is used. It only takes one parameter, which is, of course, a mandatory one to implement this function. The length of the string is returned when it becomes successful.

Syntax:

int strlen ( string $variable_name)

Here's a sample code snippet that shows the simple use of the PHP strlen() function:

Example:

<?PHP
    echo strlen('Welcome to w3schools.in');
?>

When successful execution occurs, this function returns the length of the string, including all the white spaces and special characters; Otherwise, it returns 0 when the string is empty. This function can be used in PHP version 4.0 and above.



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