-3

I want to loop this code until it prints the last value which is 51 as a single value. when I change starting value (1) and ending value (51 -> 1) to 2 and 4 it works fine.

But if the starting = ending value again this endless loop occurs.

$path = "1/40/51/"; 
while ($path != "") {

    $arr = explode("/", $path);
    $value = $arr[0];
    echo '</br>';
    echo $value;
    

    $path = str_replace($value. '/', '', $path);
    echo '</br>';
    echo $path;
}
Jeto
  • 14,596
  • 2
  • 32
  • 46
Hishan_98
  • 194
  • 1
  • 2
  • 12

2 Answers2

3

When $value == "1", $value . "/" matches 1/ at the beginning of the string, but it also matches 1/ at the end of 51/. So when you do the str_replace(), the result is 40/5.

The loop assumes that every number will be followed by /, but after that replacement it's no longer true for the last number. As a result, the replacements never remove everything, so you never reach the end condition of the loop.

Your algorithm won't work when there's a number that ends with an earlier number.

If you want to print each number in the string, just use a foreach loop.

foreach (explode('/', $path) as $value) {
    if (!empty($value)) { // skip the empty value after the last `/`
        echo "<br>$value";
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    I was just about to write a similar explanation. I don't know why, but I've seen so many people try to invent algorithms based on replacing when that's not at all what the end goal is. Don't fall into that trap. – Narf Aug 21 '20 at 19:03
  • 1
    I left out a `}` – Barmar Aug 21 '20 at 19:23
  • @Barmar need one last help how do I access the last value ( $value ) from out side the loop? – Hishan_98 Aug 21 '20 at 20:32
  • Assign another variable inside the `if`. `$last_value = $value;` – Barmar Aug 21 '20 at 20:40
  • 2
    If you're storing lists in the database like this, you should consider normalizing your design. See https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Barmar Aug 21 '20 at 20:41
2

SUGGESTION:

  1. Get out a pencil and paper
  2. Write down what you expect "$path" to equal after the first $path = str_replace($value. '/', '', $path);
  3. Write down the expected values of "$path" after the second and third loops
  4. Q: does "$path" ever become ""?
  5. Q: If not, why not?
paulsm4
  • 114,292
  • 17
  • 138
  • 190