O
O
Optimus2015-05-29 17:09:26
PHP
Optimus, 2015-05-29 17:09:26

How to repeat a loop in php?

Task: if the last element of the array == 9 then delete it
The code works:

$run = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9);
    $count_run = count($run);
    $last = $count_run-1;
    
    for ($z = 0; $z < $count_run; $z++) {

        if($z == $last && $run[$z] == 9){
            unset($run[$z]);
            sort($run);
        }
    }

Question: how if the condition worked and the last element is really equal to 9 repeat the cycle and so on until the last element != 9
It seems that recursion is needed for this, but I don’t really understand something how to use it and syntactically how to write it ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2015-05-29
Pyan @marrk2

$run = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9);
foreach($run as $key=>$val)
  if($val==9)
    unset($run[$key]);
sort($run);

V
Vladimir Martyanov, 2015-05-29
@vilgeforce

You need to place your cycle in another cycle. This loop should only terminate if the last element has not been removed. Or if there is no more data in the array. Recursion is completely unnecessary here :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question