Prev | Current Page 201 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Its prototype
looks like this:
void list(mixed...)
This construct can be particularly useful when you??™re extracting information from
a database or file. For example, suppose you wanted to format and output information
read from a text file named users.txt. Each line of the file contains user information,
including name, occupation, and favorite color with each item delimited by a vertical
bar. A typical line would look similar to the following:
Nino Sanzi|professional golfer|green
Using list(), a simple loop could read each line, assign each piece of data to a
variable, and format and display the data as needed. Here??™s how you could use list()
to make multiple variable assignments simultaneously:
// Open the users.txt file
$users = fopen("users.txt", "r");
// While the EOF hasn't been reached, get next line
while ($line = fgets($users, 4096)) {
// use explode() to separate each piece of data.
list($name, $occupation, $color) = explode("|", $line);
132 CHAPTER 5 ?–  ARRAYS
// format and output the data
printf("Name: %s
", $name);
printf("Occupation: %s
", $occupation);
printf("Favorite color: %s
", $color);
}
fclose($users);
Each line of the users.txt file will be read and formatted similarly to this:
Name: Nino Sanzi
Occupation: professional golfer
Favorite Color: green
Reviewing the example, list() depends on the function explode() to split each
line into three elements, which explode() does by using the vertical bar as the element
delimiter.


Pages:
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213