而循环测试替代

I have some really ugly code and I need help to clean it up. I'm sure there must be a better way. I have a $_POST variable with entries start_doy0, start_doy1, start_doy2 etc.

The later entries my not be filled and I need to find up to what doy they are filled. I cant start with $completed_index = -1 because there is no start_doy-1.

#Assume at least one line full, index 0.
$completed_index = 0;
 while (!empty($_POST['start_doy'.$completed_index]))
 {
 $completed_index++;
 }

# $_POST['start_doy'.$completed_index] was empty, decrement $completed_index.
$completed_index--;

Thnks, Matt

There are a couple of solutions, depending on how much you can change the calling code, and whether the start_doy fields are guaranteed to be filled in order (ie, user can't fill in start_doy9, but not start_doy2).

Option 1: Change your HTML so that the form fields are submitted with array syntax, like this:

One: <input type="text" name="start_doy[]"/><br/>
Two: <input type="text" name="start_doy[]"/><br/>

On the PHP side, this will be converted to an array, so your processing could be something like this:

<?php

$completed_indexes = array();

if(isset($_POST['start_doy']))
{
    foreach($_POST['start_doy'] as $key => $start_doy)
    {
        if(false == empty($start_doy))
            $completed_indexes[] = $key;
    }
}

echo count($completed_indexes);

?>

Option 2: Or if you can't change the HTML, or prefer this solution, you could iterate the array and check the key matches what you want:

<?php

$completed_indexes = array();

foreach($_POST as $key => $value)
{
    if(substr($key,0,9) == "start_doy" && false == empty($value))
        $completed_indexes[] = $key;
}

echo count($completed_indexes);

?>

You can remove some some brackets and change it to isset, but other then that, the code looks pretty clean to me:

$completed_index = 0; # assume at least one line full, index 0.
while(isset($_POST['start_doy'.$completed_index])) $completed_index++;
$completed_index--; # $_POST['start_doy'.$completed_index] was empty, decrement $completed_index.

you can use the "count" function like this :

$completed_index = count($_POST);

and then remove the other elements. for example if you have two other element do this :

$completed_index -=2;

Algo

$clean_post = array_filter( $_POST );

then you can simply use all post values

foreach ($clean_post as $doy => $value) {
...
}

only the non-empty values will remain in $clean_post (and this is done faster in C by a PHP function).

--

In you current algo:

  • You may want to check for 0 as well

Algo

 $completed_index = -1;
 do {
   $completed_index++;
 } while ( ! empty($_POST['start_doy' . $completed_index]));

result: $completed_index is the number of completed indexes (last index is $completed_index-1 or -1 if there is none)