String length in PHP

This tutorial covers a few things about strings in PHP:

  • the index of strings (each character has an index number)
  • how to find the length of a string (how many characters there are in a string)
  • how to ‘loop’ through each character of a string

Although this may not seem all that useful yet, being able to find the length of a string and process each character of a string is something that will become very useful later on.

Indexing and strings

In every string, each character has what is known as an index or index number. In PHP, indexing starts from the number 0. That means that the letter B in the word “Batman” has an index of 0, the second letter “a” will have an index of 1, the third letter “t” will have an index of 2 and so on… The image below shows an example of this.

strings
A string’s index.

You might, as an example, want to find out what the third character is in a string. You could do this by using its index number eg. $mystring[2]; would return the third character in the string.

Finding the length of a string

The length of a string is how many characters are in the string. The word “Batman” has 6 letters in it so its length is 6. Letters, numbers, spaces and other characters are all counted in a string. So the string “Hello world” will have a string length of 11 because there are 10 letters and 1 space in it.

As an example, finding the length of a string might be useful if you want to check how much text was entered into a form (eg. checking that a minimum of 10 characters was used for a password, or a maximum of 160 characters were used for a tweet). The strlen() function is used to find the length of a string. Eg.  strlen(“my string”); will return the length of a string. We will look at other string functions later on.

Looping through strings

A for loop can be used to go through every single character in a string and process it. In the video example, we do this to display every letter of a string on a new line. This example might not be all that useful, but there are many other ways that a for loop can be used to process characters in a string.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code for displaying the length of a string:

1
2
3
4
5
6
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 echo $nameLength;
 }
?>

Sample PHP code for displaying the third character in a string:

1
2
3
4
5
<?php
 $name = "Batman";
 echo $name[2];
 }
?>

Sample PHP code for looping through a string:

1
2
3
4
5
6
7
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 for($i=0;$i<$nameLength;$i++){
 echo $name[$i] , '</br>';
 }
?>

PHP Manual references: