Open In App

Convert a String into an Array of Characters in PHP

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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] => e
[8] => e
[9] => k
[10] => s
)

There are two methods to convert strings to an array of characters, these are:

Using str_split() Function

The str_split() function is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.

Syntax:

array str_split($org_string, $splitting_length)

Example:

PHP




<?php
 
$str1 = "Geeks";
print_r(str_split($str1));
 
$str2 = "Welcome GfG";
print_r(str_split($str2));
 
?>


Output

Array
(
    [0] => G
    [1] => e
    [2] => e
    [3] => k
    [4] => s
)
Array
(
    [0] => W
    [1] => e
    [2] => l
    [3] => c
    [4] => o
    [5] => m
    [6] => e
    [7] =>  
    [8] => G
...

Using preg_split() Function

The preg_split() function is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user.

Syntax:

array preg_split( $pattern, $subject, $limit, $flag )

Example:

PHP




<?php
 
$str1 = "Geeks";
print_r(preg_split('//', $str1 , -1, PREG_SPLIT_NO_EMPTY));
 
$str2 = "Welcome GfG";
print_r(preg_split('//', $str2 , -1, PREG_SPLIT_NO_EMPTY));
 
?>


Output

Array
(
    [0] => G
    [1] => e
    [2] => e
    [3] => k
    [4] => s
)
Array
(
    [0] => W
    [1] => e
    [2] => l
    [3] => c
    [4] => o
    [5] => m
    [6] => e
    [7] =>  
    [8] => G
...



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads