Reputation: 11
I have this problem where I can't get the value from the array in the for loop but I can access it in the while loop.
I can't seem to find a answer online, so help would be much appreciated.
while ($pos = strpos($logTxt, $char, $pos))
{
$t++;
$pos += strlen($char);
$positions[$t] = $pos;
}
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[2];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Upvotes: 0
Views: 94
Reputation: 17218
You base problem is using constant index in $positions[2]
. But your 1st line in for
loop $beginLine = $lastEndLine;
will always fail because $lastEndLine
is not defined yet. You can use smth like
// beginLine // endLine
$textToEcho = substr($logTxt, $positions[$i-1], $positions[$i]);
of course you need $positions[-1]
set to 0
before your first loop or smth like this (it's not clear what's happening before)
UPD I've tried your code and concluded
$char
is the first occurence in $logTxt
Upvotes: 0
Reputation: 8621
I think that this could be pretty easily fixed by using a foreach
loop instead of a for
loop, because it is an array.
foreach($positions as $position) {
$beginLine = $lastEndLine;
$endLine = $position;
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
If you want to use a for
loop still, I believe your problem is you are only referencing the 3rd position of the array (Key 2, as arrays start at 0), not what the loop is pointing to. You could fix it by doing this
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[$i];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Upvotes: 1
Reputation: 43441
Your $endLine
always has third element from array, because of $positions[2]
. Try changing it to $positions[$i]
Upvotes: 0