PHP strlen Function | Calculate String Length in PHP

PHP strlen is an inbuilt Function in PHP. It takes a string as parameter and returns it’s length. Also, it calculates the length by including all whitespaces and special characters in the string. In this article, we will discuss the PHP strlen Function. Also, we will discuss a few examples of using it.

Note: The function returns the number of bytes rather than the number of characters in the string.

Syntax

integer strlen (string);

Parameters

The PHP strlen Function expects only one parameter. The string whose length you want to calculate is passed as the parameter to the function. If you pass an array to the function, then it emits an E_WARNING error.

Return Value

The strlen function calculates the string length including whitespaces and special characters. If the string is empty, then the function returns 0. However, when used with arrays, it returns NULL and emits an E_WARNING error.

Input: strlen('ABCDE')
Output: 5

Input: strlen('')
Output: 0
PHP strlen Function | Calculate string length in PHP

Examples

Let’s discuss a few examples of using the PHP strlen Function to calculate the length of string.

Example 1: Simple String

<?php

	$string = 'Concatly';
	echo strlen($string);
	/*
	8
	*/

?>

In the above example, the function returns the length of string.

Example 2: Whitespaces

<?php

	$string = 'Bringing Knowledge Together';
	echo strlen($string);
	/*
	27
	*/

?>

Similarly, the PHP strlen function includes all the whitespaces while calculating the length of string. Each whitespace is counted as 1 character (or 1 byte).

Example 3: Special Characters

<?php 

    $str = "\n concatly ;"; 
      
    // here '\n' has been counted as 1  
    echo strlen($str); //12
?> 

In the above example, you can notice that the function treats the special character (‘\n’) as 1.

Example 4: Empty String or null

Similarly, the function returns 0 for an empty string or null character.

<?php 

    echo strlen("");
    // 0

    echo strlen(null);
    // 0
?> 

However, it should not be used to check whether a string is empty or null because it returns 0 in both cases.

Conclusion

In conclusion, we discussed the strlen function in this article. It calculates the string length in PHP. You can read more about it on Official PHP Documentation. Also, you can read about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *