Reputation: 3
I'm having and issue with 2 of my variables in my code. I have an if statement that rests inside a for loop. When the if statement executes in the for loop, my two variables should change accordingly, but they don't. I have no functions in my code, so all the variables are in the global scope.
Here is my code:
$file = file("../../manpages/structure.txt");
$topicindex = 0;
$topiclineindex = 0;
for($x = 0; count($file) > $x; $x++){
$data = explode(",",$file[$x]);
$structure[$topicindex][$topiclineindex] = $file[$x];
echo '[' . $topicindex . ',' . $topiclineindex . ']';
$topiclineindex += 1;
if ($data[0] == "ENDTOPIC") {
echo "NEXT TOPIC";
$topicindex += 1;
$topiclineindex = 0;
}
}
print_r($structure);
This is the output in the browser:
[0,0][0,1][0,2][0,3][0,4][0,5][0,6][0,7]NEXT TOPICArray ( [0] => Array ( [0] => TOPIC,Topic 1 [1] => SUBTOPIC,Sub Topic 1,intro.txt [2] => SUBTOPIC,Sub Topic 2,intro.txt [3] => ENDTOPIC [4] => TOPIC,Topic 2 [5] => SUBTOPIC,Sub Topic 21,intro.txt [6] => SUBTOPIC,Sub Topic 22,intro.txt [7] => ENDTOPIC ) )
And this is the contents of structure.txt
TOPIC,Topic 1
SUBTOPIC,Sub Topic 1,intro.txt
SUBTOPIC,Sub Topic 2,intro.txt
ENDTOPIC
TOPIC,Topic 2
SUBTOPIC,Sub Topic 21,intro.txt
SUBTOPIC,Sub Topic 22,intro.txt
ENDTOPIC
Any and all suggestions are very much appreciated.
EDIT: I've been testing some more, and it seems the newly assigned values don't escape the if statement. On the next iteration of the for loop, $topicindex
and $topiclineindex
returned to their previous values of the previous iteration before the if statement was excecuted.
Upvotes: 0
Views: 458
Reputation: 5776
Replace
if ($data[0] == "ENDTOPIC") {
with
if (trim($data[0]) == "ENDTOPIC") {
This will do the trick. Your IF statement is executed only for the last line because the first ENDTOPIC is actually "ENDTOPIC\n"
trim() function strips "\n"
Upvotes: 0
Reputation: 373
Your IF statement is executed only for the last line because the first ENDTOPIC is actually "ENDTOPIC\n". See http://php.net/manual/en/function.file.php for details about the new line flag
Upvotes: 1