I was wondering what how to get all the user and put all their UIDs into an array? I have seen similar questions but none really answer my question.
5 Answers
In Drupal 7 you can fetch all the users using entity_load like following,
$users = entity_load('user');
and array_keys($users) will gives you the array of uid's
You can achieve the outcome in Drupal 8 by:
$query = \Drupal::entityQuery('user');
$uids = $query->execute();
-
2Is it now recommended to use
\Drupal::entityTypeManager()
? Commented Aug 11, 2020 at 19:37 -
2
php /Drupal::entityTypeManager()->getStorage('user')->getQuery()
with dependency injection to boot preferably (I leave it as it is for clarity)– DalmazCommented Feb 5, 2021 at 13:46
Another Drupal 8 solution using \Drupal::entityTypeManager()
.
$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$query = $userStorage->getQuery();
$uids = $query
->condition('status', '1')
->condition('roles', 'moderator')
->execute();
$users = $userStorage->loadMultiple($uids);
Just sharing a snippet I created recently to get HTML and EMAIL of all existing users in the database.
Works well up to 2000+ users. After that I suggest implementing batching or an alternative direct database query.
This relies on Drupal loading each user.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user');
$html = '<table>';
$result = $query->execute();
$uids = array_keys($result['user']);
// THIS IS YOUR ARRAY OF UIDS.
$users = user_load_multiple($uids);
// EXTRA CODE.
foreach($users as $user){
$mail = $user->mail;
$name = $user->name;
$html .= '<tr><td>'.$mail.'</td>'.'<td>'.$name.'</td></tr>';
}
$html .= '</table'>;
Will return a simple html table which you can copy into excels easily etc.
To get them in an array simply use the variable stated in the code for UIDS.
To answer some of the comments: If you are working with a big number of users you won't be able to load all users in an array without timeout so you'll probably need to batch process them...
Here is how (yes it is:
function _set_batch_revench_agains_users(){
$batch = [
'operations' => [
['_revench_against_users_batch_process']
],
'finished' => '_revench_against_users_batch_finished',
'title' => t('Punishing users for ungratefulness and general insolence.'),
'init_message' => t('Batch is starting, he he he...'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('Batch has encountered an error, nooooo!'),
'file' => drupal_get_path('module', 'revench_agains_users') . '/user_agains_users.module'
];
batch_set($batch);
batch_process('admin');
}
/**
* Batch 'Processing' callback
*/
function _revench_against_users_batch_process(&$context){
//all this $context stuff is mandatory, it is a bit heavy, but the batchAPI need it to keep track of progresses
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
//don't use entity field query for such simple use cases as gettings all ids (much better performances, less code to write...)
$query = db_select('users', 'u');
$query->addField('u', 'uid');
$query->condition('u.uid', $context['sandbox']['current'], '>');
$query->orderBy('u.uid');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no users to "update", stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$uids = $query->execute()->fetchCol();
//finaly ! here is your user array, limited to a manageable chunk of 25 users
$users_array = user_load_multiple($uids);
//send it to some function to "process"...
_burn_users_burnburnburn($users_array); // I won't reveal the content of this function for legal reasons
//more mandatory context stuff
$context['sandbox']['count'] += count($uids);
$context['sandbox']['current'] = max($uids);
$context['message'] = t('burned @uid ... feels better ...', array('@uid' => end($uids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}
/**
* Batch 'finished' callback
*/
function _revench_against_users_batch_finished($success, $results, $operations) {
if ($success) {
// Here we do something meaningful with the results.
$message = t('@count users successfully burned:', array('@count' => count($results)));
drupal_set_message($message);
}
else {
// An error occurred.
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
$message = t('An error occurred while processing %error_operation with arguments: @arguments some users might have escaped !', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
drupal_set_message($message, 'error');
}
}