The line of text is separated by commas. As the line is read in (which we’ll see how to do in a later section), you’d be passing it to a variable. You’d then need to chop the text up, based on the comma. We can simulate that. First, pass the text to a variable:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
The next job is to split this text apart, so that PHP knows about all the separate pieces. The pieces we want are:
Poll number 1
To split lines of text, the gloriously sounding explode( ) function can be used. You just provided it with the text you want to split, and the character that is used to separate each piece. Here’s the syntax:
explode( separator, string_to_split )
In between the round brackets of explode( ) the separator you want to use goes first, followed by a comma, then the string you want to split. For our line of code above, you’d do this:
So we’re saying, “Look for a comma in the text, and split the line of text into separate pieces.” Once PHP does its job, it puts all the parts into the variable on the left hand side of the equals sign ( = ), which was $text_line for us. This variable will then be an array!
To get at the pieces of the array, access it in the normal manner. Here’s some code to try:
In the for loop above, we set a start value to zero. The end condition is this:
$start < count($text_line)
We use the count( ) function to get the number of elements in the array called $text_line. Each time round the loop, PHP checks to see if the value in the variable called $start is less than how many elements are in the array. It breaks out of the loop when $start is NOT less than count($text_line).
Inside the loop, we have a normal print statement:
print $text_line[$start] . "<BR>";
To get at each element in the array, this is used:
The variable called $start will be different each time round the loop. So the value at each position is printed. The “< BR >”at the end just adds a HTML line break.