1

I have this code with me and it is giving "aababc" in output i am not sure why this behaving like this.

<?php
    $str = ‘abcdefghijklmnop’;
    $fp = fopen(“output.txt”, ‘w’);
    for($i=0; $i< 4; $i++) {
    fwrite($fp, $str, $i);
    }
    ?>

Any Guru having any idea on this.

Thanks

3
  • What did you expect it to write? Commented Jun 16, 2013 at 12:31
  • 2
    Well, the 3rd parameter of fwrite is a length limit, so basically your code writes to output.txt: the first letter (i = 0, a) then the first 2 letters (i = 1, ab) and finally, when i = 3 it writes: abc with results: aababc. if you wanted to write the first 3 letters of your $str you should: fwrite($fp, $str[$i]); good luck. Commented Jun 16, 2013 at 12:32
  • It should write abc.. Commented Jun 16, 2013 at 12:33

3 Answers 3

4

Here how your for-loop works:

// i = 0;
fwrite($fp, $str, 0); // writes nothing
// i = 1;
fwrite($fp, $str, 1); // writes a
// i = 2;
fwrite($fp, $str, 2); // writes ab
// i = 3;
fwrite($fp, $str, 3); // writes abc
// total write 'aababc'

UPDATE: And to achive your goal:

for ($i = 0; $i < 4; $i++) {
   fwrite($fp, substr($str, $i, 1));
}
// will write 'abcd'

I cant stop) Or without loop:

// will take 3 first symbols from string and write to file
fwrite($fp, substr($str, 0, 3));
// will write 3 symbols from string to file
fwrite($fp, $str, 3);
Sign up to request clarification or add additional context in comments.

1 Comment

use substr to get the proper symbol you need
1

It behaves correctly.

i = 0 str = ''

i = 1 str = 'a'

i = 2 str = 'ab'

i = 3 str = 'abc'

so it writes to the end of it every time what's in $str until length $i.

Comments

0

You need to change the fwrite from this

fwrite($fp, $str, $i);

to this:

fwrite($fp, substr($str, $i, 1));

To get the expected result 'abc'

1 Comment

Nope( substr($str, $i, 1) is better)

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.