0

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;
}
1
  • 1
    Is it always $positions[2] that you need in the for loop? As it stands I don't see a reason for the for loop at all Commented Sep 20, 2017 at 19:30

3 Answers 3

1

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;

}
Sign up to request clarification or add additional context in comments.

3 Comments

$endLine = $position; plus $lastEndLine = $endLine;?
@vladkras That is a discrepancy that exists in the original code, I don't know the intentions.
Thank you, I was so fixed on that the while loop had to work that I got stuck.
0

Your $endLine always has third element from array, because of $positions[2]. Try changing it to $positions[$i]

Comments

0

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

  1. it will not work at all if $char is the first occurence in $logTxt
  2. it does the nearly the same as explode() function

2 Comments

Yes I was aware of this problem, but I needed to be able to get the variable first so i could go further.
So set $beginLine to zero at first loop, not to undefined variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.