Array input to function, a new approach
I was reading through some third party code and I had an idea of how to approach something differently. I think I've also used the method in the third party code, so now I'm questioning that, and I have a new idea. In the end it's roughly the same, but I think it's simpler. It certainly involves less tabs, which is better for readability.
Sometimes we can to do operations in bulk on an array rather than just on a single value. For example, let's assume we want to do something to a number of database entries.
As an example, let's assume we want to ban users. Here's what the standard way would look like:
PHP Code:
function banusers($users) {
if (!is_array($users)) {
$users = array($users); //make a single input into an array
}
foreach($users as $user) {
if (/*$user is a valid input and permissions are right*/) {
/*actually ban the user here*/
}
}
}
That's fine, but the more I think about it, that's counterintuitive. Why force an array when the goal is to operate on individual items?
Would this be more logical?
PHP Code:
function banuser($user) {
if (is_array($user)) {
foreach($user as $u) {
banuser($u);
}
}
if (/*$user is a valid input and permissions are right*/) {
/*actually ban the user here*/
}
}
Shouldn't the multiple variant be the exception?
Again, I'm just thinking out loud here. Either one works, and this isn't a "problem" to be solved.