PHP program to split a given comma delimited string into an array of values

PHPServer Side ProgrammingProgramming

To split a given comma delimited string into an array of values, the PHP code is as follows −

Example

 Live Demo

<?php
$my_string = "456,789,23, 4, 019";
$my_str_arr = preg_split ("/,/", $my_string);
print_r("The array is ");
print_r($my_str_arr);
$my_string = "00, 876, 5432, 1234, 0";
$my_str_arr = explode (",", $my_string);
print_r("The array is ");
print_r($my_str_arr);
?>

Output

The array is Array
(
   [0] => 456
   [1] => 789
   [2] => 23
   [3] => 4
   [4] => 019
)
The array is Array
(
   [0] => 00
   [1] => 876
   [2] => 5432
   [3] => 1234
   [4] => 0
)

A string of numbers is defined and the ‘preg_split’ function is used to separate the numbers based on the occurance of ‘/’ or ‘.’. The split array is now printed. Another method to split the given number in the form of a string is to use the explode function. It splits the array based on the occurance of a comma.

raja
Published on 02-Jul-2020 10:24:00
Advertisements