Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix while loop?

I’m trying to learn php. I thought of doing a simple app to divide a text for Twitter threads.

For simplicity, I want to divide the text at a space closest to 20 characters.

I tried using strpos() with offset like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$str = "The main application of de Sitter space is its use \in general relativity, where it serves as one of the simplest mathematical models of the universe;

while ($pos < 20) {
    $findme = ' ';
    $pos = strpos($str, $findme);
    $posOffset = $pos+1;
    $pos = strpos($str, $findme, $posOffset);
}

But this goes into an infinite loop?

What am I doing wrong.

>Solution :

The issue with your original implementation is that you always reset the value of $pos to the first match with the first call to strpos(). So from 8 to 3 with each new iteration of your loop. So you actually never search beyond the second blank in the string. Which of course means that the loop will never terminate, since you always search in the same first 9 characters of the input string.


That probably is what you are looking for:

<?php
$input = "The main application of de Sitter space is its use \in general relativity, where it serves as one of the simplest mathematical models of the universe.";
$output=[];

do {
    $pos = 0;
    do {
        // note: we add a trailing blank to the end of the search subject to guarantee a match
        $pos = strpos($input . ' ', ' ', $pos + 1);
    } while  ($pos < 20);
    $output[] = substr($input, 0, $pos);
    $input = substr($input, $pos + 1);
} while (strlen($input) > 0);

print_r($output);

The output is:

Array
(
    [0] => The main application
    [1] => of de Sitter space is
    [2] => its use \in general relativity,
    [3] => where it serves as one
    [4] => of the simplest mathematical
    [5] => models of the universe.
)

Note however that searching for ' ' (the space character) is not really a robust strategy. Instead you should search for any white space character there is. Which includes tab characters for example, something your approach would be blind towards.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading