Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to remove the first character of string in PHP?
Next article icon

How to read each character of a string in PHP ?

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. 

Here are some approaches to read each character of a string in PHP

Table of Content

  • Using str_split() method - The str_split() method
  • Using strlen() method - The strlen() method
  • Using preg_split()
  • Using mb_strlen and mb_substr

Approach 1: Using str_split() method - The str_split() method

Using str_split() method - The str_split() method is used to split the specified string variable into an array of values, each of which is mapped to an index value beginning with 0. This method converts the input string into an array.

str_split(str)

 PHP foreach loop iteration can then be done over the array values, each of which element belongs to a character of the string. The values are then printed with a space in between each. 

Example:

PHP
<?php    // Declaring string variable  $str = "Hi!GFG User.";  echo("Original string : "); echo($str . "</br>");  $array = str_split($str); echo("Characters : ");  foreach($array as $val){     echo($val . " "); }  ?> 

Output:

Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .

Approach 2: Using strlen() method - The strlen() method

Using strlen() method - The strlen() method is used to compute the length of the specified string in PHP. A for loop iteration is applied using the length of the string, and the ith index character is printed each time. The time complexity is the same as the previous method. However, no extra space is required to store the string in the form of the array object. 

strlen(str)

Example:

PHP
<?php    // Declaring string variable  $str = "Hi!GFG User.";  echo("Original string : "); echo($str."</br>"); echo("Characters : ");  // Iterating over the string  $len = strlen($str);  for ($i = 0; $i < $len; $i++){     echo ($str[$i]." "); }  ?> 

Output:

Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .

Approach 3: Using preg_split()

Using preg_split() in PHP splits a string into an array of characters with a regular expression. By splitting with //u, it handles each character, including multibyte characters, properly. This allows easy iteration through each character in the resulting array.

Example: In this example we splits the string "Hello, World!" into individual characters and prints each character on a new line using a foreach loop with preg_split and Unicode support.

PHP
<?php $string = "Hello, World!"; $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);  foreach ($chars as $char) {     echo $char . "\n"; } ?> 

Output
H e l l o ,   W o r l d ! 

Approach 4: Using mb_strlen and mb_substr

Using mb_strlen and mb_substr functions is especially useful for strings with multibyte characters. The mb_strlen function returns the number of characters in the string, and mb_substr is used to retrieve a specific character from the string based on its position.

Example: In this example, we will use mb_strlen and mb_substr method

PHP
<?php  // Declaring string variable  $str = "Hi!GFG User.";  echo("Original string : "); echo($str . "\n"); echo("Characters : ");  // Getting the length of the string with mb_strlen $len = mb_strlen($str, 'UTF-8');  // Iterating over the string using mb_substr for ($i = 0; $i < $len; $i++) {     echo (mb_substr($str, $i, 1, 'UTF-8') . " "); }  ?> 

Output
Original string : Hi!GFG User. Characters : H i ! G F G   U s e r .  

Approach 5: Using str_split() with Length Parameter

The str_split() function can be used with an optional second parameter that specifies the length of each chunk. By setting this length to 1, the function effectively splits the string into an array of individual characters.

Example

PHP
<?php  function readCharacters($string) {     // Split the string into an array of characters     $characters = str_split($string, 1);          // Print each character with a space in between     foreach ($characters as $char) {         echo $char . ' ';     } }  $inputString = "Hi!GFG User."; echo "Original string: " . $inputString . "\n"; echo "Characters: "; readCharacters($inputString); ?> 

Output
Original string: Hi!GFG User. Characters: H i ! G F G   U s e r . 

Next Article
How to remove the first character of string in PHP?

M

mallikagupta90
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP-string
  • PHP-function
  • PHP-Questions

Similar Reads

  • How to get the last character of a string in PHP ?
    In this article, we will find the last character of a string in PHP. The last character can be found using the following methods. Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, i
    2 min read
  • How to remove the first character of string in PHP?
    Remove the very first character of a given string in PHP Examples: Input : GeeksforgeeksOutput : eeksforgeeksInput :, Hello geek!Output : Hello geek!Explanation: In PHP to remove characters from the beginning we can use ltrim but in that, we have to define what we want to remove from a string i.e. r
    3 min read
  • How to get the position of character in a string in PHP ?
    In this article, we will get the position of the character in the given string in PHP. String is a set of characters. We will get the position of the character in a string by using strpos() function. Syntax: strpos(string, character, start_pos) Parameters: string (mandatory): This parameter refers t
    2 min read
  • How to replace multiple characters in a string in PHP ?
    A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP. Using the str_repl
    3 min read
  • How to get string between two characters in PHP ?
    A string is a sequence of characters stored in the incremental form in PHP. A set of characters, one or many can lie between any two chosen indexes of the string. The text between two characters in PHP can be extracted using the following two methods : Table of Content Using substr() Method: Using f
    4 min read
  • How to check if a String contains a Specific Character in PHP ?
    In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
    2 min read
  • How to extract Numbers From a String in PHP ?
    Extracting numbers from a string involves identifying and isolating numerical values embedded within a text. This process can be done using programming techniques, such as regular expressions, to filter out and retrieve only the digits from the string, ignoring all other characters. Here we have som
    3 min read
  • How to replace String in PHP ?
    Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each
    3 min read
  • How to Convert Number to Character Array in PHP ?
    Given a number, the task is to convert numbers to character arrays in PHP. It is a common operation when you need to manipulate or access individual digits of a number. This can be particularly useful in situations where you need to perform operations on the digits of a number, such as digital root
    3 min read
  • Concatenation of two strings in PHP
    In this article, we will concatenate two strings in PHP. There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences