Is there an atomic way to update_option in WordPress (to ensure data integrity)?

I want to update an option which is an array by adding a new value, but there’s no atomicity or guarantee of data integrity.

EXAMPLE

Read More
//Get the option value (an array)
$val = get_option( "some-option" );

//Add to the array
$val[] = "something";

/** Here, another session might already have it and is calling "update_option" */

//Save back (this overwrites whatever that other person did)
update_option( "some-option", $val );

Is there anything in wordpress that offers atomicity?

Related posts

Leave a Reply

1 comment

  1. My first thought was to add a second option that acts as a data lock.

    You’d perform a check to see if the lock came back false before being allowed to modify the option.

    After giving it some more thought however wouldn’t a custom table better suit your needs. If you have multiple people updating the same option a table makes more sense.

    Anyway, here’s how the lock could work:

    if ( false === get_option( 'some-option-lock' ) )  {
        update_option( 'some-option-lock', true );
    
        $val = get_option( "some-option" );
    
        //Add to the array
        $val[] = "something";
    
        update_option( "some-option", $val );
    
        update_option( 'some-option-lock', false );
    }