How to put string in array, split by new line in PHP ?

Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are spitted by the newline.

Example:

 Input : string is 'Ankit \n Ram \n Shyam'
 Output : Array
(
    [0] => Ankit
    [1] => Ram
    [2] => Shyam
)

Using explode() Function: The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string. This function accepts separator and string to be separated and optional argument length of string to be separated.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// PHP program to separate string
// using explode function
  
// String which to be converted
$str = "Ankit Mishra\nRam Singh\nShyam Pandey";
  
// Function to convert string to array
$arr = explode("\n", $str);
  
// Print the information of array
print_r($arr);
?>

chevron_right


Output:



Array
(
    [0] => Ankit Mishra
    [1] => Ram Singh
    [2] => Shyam Pandey
)

Using preg_split() Function: The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it. This function takes first argument as regular expression which is used for splitting second argument is as string which is to be splitted.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// A php program to separate string
// using preg_split() function
  
// String which to be converted
$str = "Ankit Mishra\nRam Singh\nShyam Pandey";
  
// This function converts the string
$arr= preg_split ('/\n/', $str);
  
// print the information of array
print_r($arr);
?>

chevron_right


Output:

Array
(
    [0] => Ankit Mishra
    [1] => Ram Singh
    [2] => Shyam Pandey
)


My Personal Notes arrow_drop_up

All powers are within you You can do anything and everything Believe in that

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.