How can I get a random username from my first array, but the username selected shouldn't be in the "denied usernames Array" in PHP
Array of usernames
Array (
[0] => stdClass Object ( [user_login] => emma88 )
[1] => stdClass Object ( [user_login] => milli )
[2] => stdClass Object ( [user_login] => [email protected] )
[3] => stdClass Object ( [user_login] => shawn )
[4] => stdClass Object ( [user_login] => shawnfao2 )
)
2021-03-23
2021-03-23
denied usernames Array:
Array (
[0] => Array ( [username] => emma88 )
[1] => Array ( [username] => milli )
[2] => Array ( [username] => [email protected] )
)
My Answer:
You can achieve this by first filtering out the denied usernames from the first array and then selecting a random username from the filtered array. Here's how you can do it:
php
// Array of usernames
$usernames = [
(object) ['user_login' => 'emma88'],
(object) ['user_login' => 'milli'],
(object) ['user_login' => 'test@example.com'],
(object) ['user_login' => 'shawn'],
(object) ['user_login' => 'shawnfao2']
];
// Denied usernames array
$deniedUsernames = [
['username' => 'emma88'],
['username' => 'milli'],
['username' => 'test@example.com']
];
// Filter out denied usernames
$filteredUsernames = array_filter($usernames, function($username) use ($deniedUsernames) {
foreach ($deniedUsernames as $denied) {
if ($username->user_login === $denied['username']) {
return false;
}
}
return true;
});
// Get a random username from the filtered array
$randomUsername = $filteredUsernames[array_rand($filteredUsernames)]->user_login;
echo $randomUsername;
This code will first filter out the denied usernames from the `$usernames` array and then select a random username from the filtered array.
Rate this post
4 of 5 based on 8547 votesComments