mardi 20 septembre 2016

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.

Aucun commentaire:

Enregistrer un commentaire