To find length of string in php, it’s very simple you can use the PHP strlen() function to get the length of a string. The strlen() function return the length of the string on success, and 0 if the string is empty.
But whenever someone asked to how to find length of string without using string function in php then you should know this. Because you are a developer so you should know basic fundamental of string and computer science.
In this article, we will find length of string in both ways. Mean using inbuilt function as well programmatically.
Let’s see an example
Using inbuilt function
<?php
$str = "this is my first program";
//simply find the length of string using inbuild function:
echo "Length of : <b> $str </b> : using strlen inbuild function is - ".strlen($str);
?>
Also Read,
- Reverse number in PHP without using function
- php interview questions and answers
- swap 2 variables without using third variable
- Reverse string without using built in function in php
- how to find and replace string in php
Using programatically
<?php
$str = "this is my first program";
$i = 0;
while (@$str[$i++] != NULL);
$i--;
echo "Length of : <b> $str </b> is : $i (programatically)";
?>
Let’s understand logic
- As you know, that string is a sequence of character, so that why it an array by default so, therefor end of string there is NULL value assigned it by default. So here string stored in $str variable.
- we will declare a variable $i = 0 and run while until end of that string, find the length of string by incremented the value of $i
- Finally, we decreased 1 from the total length of string and print it using echo, it will show actual length of string.