Monday, 14 October 2019

Using the Explode Function to Get Data from a String in PHP

PHP 

The function explode(string $delimiter, string $string [, int $limit = PHP_INT_MAX]):array in PHP can be used to split a string by a string. The usage of the function can be referred to the PHP:explode - Manual. It is convenient to use this function to get data from a raw text file.

Suppose we have a text data file called data.txt that stores the students' scores of math and English like this:

ID|Name|Math|English|Class
1001|Carpenter Tia|85|90|Y5
1002|Holt Evan|88|80|Y5
1003|April Bott|70|92|Y5
1004|Kristen Lefebvre|65|80|Y5
1005|Janice Thrash|72|75|Y5
1006|Jeffrey Lu|68|79|Y5
1007|Shirley Smith|80|78|Y5
1008|Gabe Tang|74|73|Y5
1009|David Pauls|69|75|Y5
1010|Melissa Wong|82|80|Y5

We can use the explode() function to extract data from this plain text file as below.

$file = fopen('data.txt', 'r');

//ignore the title line
fgets($file);
$mathTotal = 0;
$englishTotal = 0;
$i = 0;
while (!feof($file)) {
    $record = fgets($file);
    //extract data to an array
    $data = explode('|', $record);
    //calculate the total score of math
    $mathTotal += floatval($data[2]);
    //calculate the total score of English
    $englishTotal += floatval($data[3]);
    $i++;
}

echo 'Math total: '. $mathTotal.'<br>';
echo 'Math average: '. $mathTotal/$i.'<br>';
echo 'English total: '. $englishTotal.'<br>';
echo 'English average: '. $englishTotal/$i.'<br>';

fclose($file);


In line 4, the first line of the text file is read. Since it is the title line, the data is ignored. In line 11, we set the delimiter, |, and extract the data from a string by using the explode() function. Then, the math and the English scores of each student can be accessed in the array $data's position of 2 and 3 respectively. Finally, the total and the average scores of math and English are printed out.



Search