How to create an array from PHP string? Explain with example?

Posted by

we can create an array from php string with the help of str_split( ) function in PHP, str_split() is an inbuilt function in PHP and 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.

stntax

array str_split($orginal_string, $splitting_length)

This function take two parameters

  • $original_string=  the original string that the user needs to split into an array.
  • $splitting_length=  the length of each array element

example

<?php

  //without using length
$string = "SHIVAM";
  
   echo "<pre>";
print_r(str_split($string));
    echo "<pre>";

           /* OR */
  
//with length
$string = "COTOCUSFAMILY";

  echo "<pre>";
print_r(str_split($string, 3));
   echo "<pre>";

?>

output

Array
(
    [0] => S
    [1] => H
    [2] => I
    [3] => V
    [4] => A
    [5] => M
)
Array
(
    [0] => COT
    [1] => OCU
    [2] => SFA
    [3] => MIL
    [4] => Y
)
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x