Benn
Benn

Reputation: 5023

How to generate/delete number suffix that follows the number sequence? PHP

I am working on widget area ( sidebars ) generator that automatically adds a number suffix to the widget area name.

Desired sidebars names output when created should be

custom_sidebar_area1
custom_sidebar_area2
custom_sidebar_area3
...

If custom_sidebar_area2 is deleted

custom_sidebar_area1
custom_sidebar_area3

the next created sidebar should be again

custom_sidebar_area2 

the one after is than custom_sidebar_area4

The issue:

This snippet currently works for creation and is saved in an array of areas and suffix index to keep track for the next number,

$custom_sidebars = get_theme_mod( 'custom_sidebars' );
$new_sidebar_name = $_POST['newSidebarName'];
$suffix = $custom_sidebars ? intval( $custom_sidebars['suffix'] ) + 1 : 1;

$custom_sidebars['areas']['custom_sidebar_area' . $suffix] = $new_sidebar_name ;
$custom_sidebars['suffix'] = $suffix;

when saved this is the array output

array
(
    [areas] => array
    (
        [custom_sidebar_area5] => 'Title'
        [custom_sidebar_area6] => 'New widget area'
    )
    [suffix] => 6
)

now this works perfect for creation , but I need the deletion of the sidebar to follow the order and update the suffix accordingly.

If I used something like this

    $old_sidebar_name = $_POST['oldSidebarName'];
    $custom_sidebars = get_theme_mod( 'custom_sidebars' );
    $suffix = $custom_sidebars ? intval( $custom_sidebars['suffix'] ) - 1 : 1;

    unset( $custom_sidebars['areas'][$old_sidebar_name] );

    $custom_sidebars['suffix'] = $suffix;

the order works until you start skipping the deletion and instead deleting last in order you delete the number 2. Than the next created sidebar can override the existing one.

If I dont use the suffix change when deleting , the suffix will always increase , and user that has previously deleted ALL of the created sidebars (let say there was 5 ), on new sidebar creation will have

custom_sidebar_area6

instead

custom_sidebar_area1

What would be best approach to get out of this ? Any help is appreciated.

Upvotes: 0

Views: 49

Answers (1)

Dan
Dan

Reputation: 11104

You can create a function that scans the current array to determine an available suffix.

Here is the little test I setup that works as expected:

$a = array('a1'=>1, 'a2'=>2, 'a3'=>4);
function getSuffix($a){
    for($i=1; $i<=count($a)+1; $i++ ){
        if( ! array_key_exists("a$i", $a) ){
            return $i;    
        }    
    }
}

Then this line:

 $suffix = $custom_sidebars ? intval( $custom_sidebars['suffix'] ) - 1 : 1;

can become:

$suffix = $custom_sidebars ? getSuffix($custom_sidebars['area']) : 1;

Upvotes: 1

Related Questions