How to Iterate Over Characters of a String in PHP ?
Last Updated :
18 Jul, 2024
This article will show you how to iterate over characters of string in PHP. It means how to loop through an array of characters in a string. There are two methods to iterate over the character of a string, these are:
Using str_split() function and foreach Loop
The str_split() function converts the given string into an array and then uses foreach loop to iterate over an array of elements.
Syntax:
$chars = str_split($str);
foreach ($chars as $char) {
echo $char . "\n";
}
Example: This example uses str_split() function and foreach Loop to iterate over characters of string.
PHP
<?php
// Declare an array
$str = "GeeksforGeeks";
$chars = str_split($str);
foreach ($chars as $char) {
echo $char . "\n";
}
?>
OutputG
e
e
k
s
f
o
r
G
e
e
k
s
Using for Loop
The for loop is used to iterate the array elements and execute the block. The for loop contains the initialization expression, test condition, and update expression (expression for increment or decrement).
Syntax:
for ($i = 0; $i < strlen($str); $i++) {
echo $str[$i] . "\n";
}
Example: This example uses for loop to iterate over characters of string.
PHP
<?php
// Declare an array
$str = "GeeksforGeeks";
for ($i = 0; $i < strlen($str); $i++) {
echo $str[$i] . "\n";
}
?>
OutputG
e
e
k
s
f
o
r
G
e
e
k
s
Using mb_substr() with while loop
Using mb_substr() with a while loop in PHP involves determining the string length with mb_strlen() and iterating through each character using mb_substr(), ensuring correct handling of multi-byte characters for accurate iteration.
Syntax:
while ($i < $len) {
$char = mb_substr($str, $i, 1, 'UTF-8');
echo $char . "\n";
$i++;
}
Example:
PHP
<?php
$str = "GeeksforGeeks";
$len = mb_strlen($str, 'UTF-8');
$i = 0;
while ($i < $len) {
$char = mb_substr($str, $i, 1, 'UTF-8');
echo $char . "\n";
$i++;
}
?>
Output:
G
e
e
k
s
f
o
r
G
e
e
k
s
Using preg_split() with foreach Loop
In this approach, we utilize the preg_split() function to split the string into an array of characters based on a regular expression pattern. We then use a foreach loop to iterate over each character in the resulting array.
Syntax:
$chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $char) {
// code here...
}
Example:
PHP
<?php
$str = "HelloWorld";
$chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $char) {
echo $char . "\n";
}
// Nikunj Sonigara
?>
OutputH
e
l
l
o
W
o
r
l
d
Using strpbrk() with While Loop
In this approach, strpbrk() function is used to find the first occurrence of any of the specified characters in a string. By repeatedly removing the first character, we can iterate over each character in the string.
Example:
PHP
<?php
$str = "GeeksforGeeks";
while ($str !== false && $str !== '') {
$char = $str[0];
echo $char . "\n";
$str = substr($str, 1);
}
?>
OutputG
e
e
k
s
f
o
r
G
e
e
k
s
Using strtok with While Loop
Another valid approach to iterate over characters of a string in PHP is by using the strtok function in combination with a while loop. The strtok function tokenizes a string, and by specifying an empty string as the delimiter, it allows us to iterate over each character one by one.
Example:
PHP
<?php
function iterateWithStrtok($str) {
$token = strtok($str, '');
while ($token !== false) {
echo $token . "\n";
$token = strtok('');
}
}
$inputString = "GeeksforGeeks";
iterateWithStrtok($inputString);
?>
Similar Reads
How to find number of characters in a string in PHP ?
We have given a string and the task is to count number of characters in a string str in PHP. In order to do this task, we have the following methods in PHP:Table of ContentMethod 1: Using strlen() MethodMethod 2: Using mb_strlen() MethodMethod 3: Using iconv_strlen() MethodMethod 4: Using grapheme_s
3 min read
How to Iterate Over an Array in PHP?
Arrays are fundamental data structures in PHP, and the ability to iterate through them is crucial for manipulating and processing data. In this article, we will explore various approaches to iterate through arrays in PHP.Table of ContentUsing for LoopUsing foreach LoopUsing while Loop with each() Fu
3 min read
How to get the last n characters of a PHP string?
Write a PHP program to get last n characters of a given string. Examples: Input : $str = "GeeksforGeeks!" $n = 6 Output : Geeks! Input : $str = "GeeksforGeeks!" $n = 9 Output : forGeeks! Method 1: Tn this method, traverse the last N characters of the string and keep appending them in a new string. E
1 min read
How to add a Character to String in PHP ?
Given two strings, the task is to add a Character to a String in PHP. The character can be added to a string in many ways in this article we will be using eight methods including the Concatenate Method, the String Interpolation Method, the str_pad() Method, Concatenation Assignment (.=) Operator, St
5 min read
How to remove all non-printable characters in a string in PHP?
Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to
2 min read
Convert a String into an Array of Characters in PHP
Given a string, the task is to convert the string into an array of characters using PHP. Examples:Input: str = "GFG" Output: Array( [0] => G [1] => f [2] => G)Input: str = "Hello Geeks"Output: Array( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => G [7] =>
4 min read
How to remove control characters from PHP string ?
Given a string that contains control characters. The task is to remove all control characters from a string. In ASCII, all characters having a value below 32 come under this category. Some of the control characters are given below: S.NO ASCII VALUE Name Symbol 1. 0 null (NUL) "\0" 2. 9 horizontal ta
2 min read
How to Insert Characters in a String at a Certain Position in PHP ?
You will learn how to insert characters into a string at a specific position in PHP. Given a string str and an integer position that describes the index in the original string where the desired string insertStr will be added. This can be achieved using various approaches, such as string concatenatio
3 min read
How to count the number of words in a string in PHP ?
Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:Table of ContentUsing str_word_count() MethodUsing trim(), preg_replace(), count() and explode() method. Using trim(), substr_count(), and
4 min read
How to extract numbers from string in PHP ?
Extracting numbers from a string in PHP involves isolating numeric values within mixed text. This is essential for data validation, processing, and analysis, allowing developers to retrieve and utilize numerical information from user input, database entries, or external sources, ensuring accurate an
3 min read