Shawn Dibble Shawn Dibble - 2 months ago 4
PHP Question

Dynamically building an if statement based on the number of array keys present

I have a PHP function in which I pass in a string or array of column names. Unfortunately, this can become a bit problematic and cumbersome depending on the number of column names that I get.

As such, is there a way that I can rewrite my if statement so that I dynamically can build the conditional based on the number of elements I have in my array?

I would usually run a check to see if a value was in the array, however as these are key values of another array, it makes things more complicated. Below is my current code.

private function pushToArray($list, $columnName, $date) {
$array = [];
foreach($list as $item) {
if (is_array($columnName)){
if ($date == $item[$columnName[0]] || $date == $item[$columnName[1]]) {
array_push($array, $item);
}
} else {
if ($date == $item[$columnName]) {
array_push($array, $item);
}
}
}
return $array;
}


As can be seen here, as my array increase in elements, I would have to add additional if conditions to handle the larger array set. Something I would like to avoid.

EDIT:
Right now, I am using laravel as the framework for my application. I am trying to generate an array that will populate a view of an upcoming event system.
Here is a sample of the current calls:

$separatedArray = $this->pushToArray($this->separatedList(), 'destroyed_date', $currentDate);
$travelsArray = $this->pushToArray($this->travelsList(), ['leave_date','return_date'], $currentDate);
$trainingUsersArray = $this->pushToArray($this->trainingUsersList(), 'due_date', $currentDate);


Here is a sample of some of the code before I moved it to its own function.

$separatedArray = $travelsArray = $trainingUsersArray = [];
$currentDate = $date->format('Y-m-d');

foreach($separatedList as $user) {
if ($currentDate == $user->destroyed_date) {
array_push($separatedArray, $user);
}
}

foreach($travels as $travel) {
if ($currentDate == $travel->leave_date || $currentDate == $travel->return_date) {
array_push($travelsArray, $travel);
}
}
foreach($trainingUsers as $trainingUser) {
if ($currentDate == $trainingUser->due_date) {
array_push($trainingUsersArray, $trainingUser);
}
}

Answer

Replace code of first if block with foreach loop.

if (is_array($columnName)) {
    foreach ($columnName as $column) {
        if ($date == $item[$column]) {
            array_push($array, $item);
        }
    }
}
Comments