How leave selected checkboxes marked after they are selected and saved in the database

You can use get_option() to retrieve the selected role(s) that were saved in the database, then use checked() in your checkboxes. E.g.

// In your code, after this line:
$roles = $wp_roles->get_names();

// Add this which retrieves and stores the selected role(s):
$selected_roles = (array) get_option( 'choosed_users_role' );

/* And then in your <input>, use checked() with in_array():
<input name="role[]" type="checkbox" id="user_role-<?php echo $i; ?>" value="<?php echo $role;?>"
  <?php checked( in_array( $role, $selected_roles ) ); ?>>
*/

Additional Notes

  • If you used the settings API to create the options page, you wouldn’t need to manually call update_option() to save the selected role(s).

  • $i is never declared in your code, so you should declare it before the foreach begins.

  • WP_Roles::get_names() returns an associative array with role slug and name pairs, e.g. 'administrator' => 'Administrator' or 'foo_role' => 'Foo Role', so I suggest you to save the role slug and not the name.

  • I would use wp_roles() like so: $roles = wp_roles()->get_names(), which means you don’t need to access the global $wp_roles variable.