Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
