phparraysmaxtext-extractionsuffix

Get highest qualifying key suffix from form submission array


We have a form in which input is added dynamically. From the form submit page, we will get the following result

print_r($_POST)

['wind_1']=hk
['wind_2']=pop
etc etc 

['wind_25']=another

Here we need to get the last key number, that is wind_n, here: n=25

here the last input is ['wind_25'] that's why n=25


Solution

  • Since user supplied data should always be considered untrustworthy, when processing the payload, use strict validation before honoring the array keys. Bear in mind that the keys might be mutated or reordered without your consent.

    Code: (Demo)

    $_POST = [
        'wind_1' => 'hk',
        'hamburger_66' => 'foo',
        'wind_2' => 'pop',
        'wind_25' => 'another',
        'wind_13' => 'bar',
        'pass_wind_99' => 'stank',
    ];
    
    $n = null;
    foreach ($_POST as $k => $v) {
        if (sscanf($k, 'wind_%d', $windInt) && $windInt > $n) {
            $n = $windInt;
        }
    }
    var_export($n);
    

    Otherwise, it is more succinct and less efficient to use a regex pattern and make three cycles over the array.

    Code: (Demo)

    var_export(
        (int) max(
            preg_filter(
                '/^wind_(\d+)$/',
                '$1',
                array_keys($_POST)
            )
        )
    );