Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove array from array inside get_option

So I’m using the WordPress get_option() to get my database option of an array of users.

So I have the following method:

    public function deauthorize_instagram_via_button()
    {
        if (!get_option('instagram_authenticated_users')) {
            return;
        }
        $users = get_option('instagram_authenticated_users');
        
        // If we have single entry, delete the option from the database
        if (count($users) === 1) {
            delete_option('instagram_authenticated_users');
            $this->instagram->delete_cache();
        }

        // This returns the user_id
        var_dump($_POST['user_id']);
        die();

        // delete_option('instagram_authenticated_users');
        exit;
    }

Where get_option('instagram_authenticated_users') returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array(2) {
  [0]=>
  array(5) {
    ["username"]=>
    string(9) "sem_test1"
    ["user_id"]=>
    int(17841400835712753)
  }
  [1]=>
  array(5) {
    ["username"]=>
    string(12) "sem_test2"
    ["user_id"]=>
    int(17841449642220098)
  }
}

Then I have a $_POST['user_id'] which returns user_id => 17841449642220098.

How can I search through the array and remove that user_id‘s array and then call update_option('instagram_authenticated_users') so that I keep just one single array inside the array.

So after it gets remove, the get_option('instagram_authenticated_users') will look like this when called:

array(2) {
  [0]=>
  array(5) {
    ["username"]=>
    string(9) "sem_test1"
    ["user_id"]=>
    int(17841400835712753)
  }
}

Thanks all!

>Solution :

You can use array_filter like below:

// get current list
$users = get_option('instagram_authenticated_users');

// filter out POST user id
$filtered_users = array_filter($users, function($user){
    return $user["user_id"] !== (int) $_POST['user_id'];
});

// save filtered array
update_option('instagram_authenticated_users', $filtered_users);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading