Chapter 41 More with Files

41.1 Exercises of a General Nature with Files

Exercise 41.1-1 Calculating the Sum of 10 Numbers

Suppose there is a file named “f_data41.1-1.txt” that contains 10 3-digit integers (separated by a single space character). An example of the structure of the file is shown here.

131 500 122 152 127 191 111 290 156 161

Write a PHP script that calculates and displays their sum.

Solution

There are two approaches to iterate through the numbers of this file.

First approach

In this approach, a string variable named $values gets the content of the whole line of the file. Then, the substr() function is used in a for-loop to split the content into individual three-digit numbers. These numbers are then converted to integers using ...

Get PHP and Algorithmic Thinking for the Complete Beginner now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.