Search code examples
phpvariableskeysequential

Cleanest way of working out next variable name based on sequential order?


Hope my title explains it ok! Here's more detail:

I'm creating an array which stores keys & their values. Eg.

test1 = hello
test2 = world
test3 = foo

What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.

In the example below I want the next key to be 'test46', as it is the next highest value:

test6 = blah
test45 = boo
test23 = far

Solution

  • Implementation of @alex answer without using a loop:

    $arr = array('test6', 'test45', 'test23');
    $max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
    
    $newKey = 'test' . ++$max; // string(6) "test46"
    

    CodePad