Drupal - Get a list of all users and into an array

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();

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.

Tags:

Users