Reading and storing a list as an array PHP

In PHP, you can read and store a space-separated string of values as an array using several methods. The most efficient approach is using the explode() function, though you can also manually parse using loops.

Using explode() Function

The simplest and most efficient method to convert a space-separated string into an array ?

<?php
$list = "10 20 30 40 50 60";
$arr = explode(" ", $list);

foreach($arr as $value) {
    echo $value . "<br>";
}
?>
10
20
30
40
50
60

Using Manual Parsing with Loop

You can also manually parse the string character by character to build the array ?

<?php
$list = "10 20 30 40 50 60";
$arr = [];
$current_number = "";

for($i = 0; $i < strlen($list); $i++) {
    if($list[$i] !== " ") {
        $current_number .= $list[$i];
    } else {
        if($current_number !== "") {
            $arr[] = $current_number;
            $current_number = "";
        }
    }
}

// Add the last number
if($current_number !== "") {
    $arr[] = $current_number;
}

foreach($arr as $value) {
    echo $value . "<br>";
}
?>
10
20
30
40
50
60

Comparison

Method Code Length Performance Readability
explode() Short Fast High
Manual Loop Long Slower Medium

Conclusion

Use explode() for splitting strings into arrays as it's built-in, efficient, and readable. Manual parsing is useful when you need custom logic or handling of complex delimiter patterns.

Updated on: 2026-03-15T09:33:10+05:30

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements