Kevin
Kevin

Reputation: 61

Processing multiple variables in a single function PHP

I'm pretty new and need guidance on how to approach a simple problem.

I'm building an app in PHP to allow different views of Fantasy Premier League (FPL) team data. I'm pulling data from an API (JSON array), looping through it, and storing it in a db. One of the API calls needs a team_id to pull that team's respective players.

My initial thinking is to write a function that takes the team_id as an argument, then parses the data to insert into the db. But how would I pass each of 12 different team_ids to the function to be processed without repeating the function 12 times for each team_id?

So, I might have:

$team_id_1 = 1;
$team_id_2 = 2;
$team_id_3 = 3;
etc...

Then my function might be:

function insert_team_data($team_id) {

$fplUrl = 'https://fantasy.premierleague.com/api/entry/' . $team_id . '/event/29/picks/';

foreach ($team_data as $key => $value) {
    # code...
}

$sql = "INSERT INTO ..."

}

Is it possible to construct this in a way where each team_id gets passed to the function iteratively in a single process (i.e. without repeating the function code for each team_id)? Would I create an array of the team_ids and have the function loop through each one, then loop through each resulting team's data?

Upvotes: 2

Views: 63

Answers (1)

Sherif
Sherif

Reputation: 11943

Yes, you can do either: use an array or a variadic function.

The way you're thinking of doing it is what's called a variadic function or variable-length function.

It can be achieved through either the use of func_get_args() or the splat operator, which handles argument packing/unpacking.

Here's an example.

function insert_team_data(... $team_ids) {

    // $team_ids will appear as an array in your function    
    foreach ($team_ids as $team_id) {
        $fplUrl = "https://fantasy.premierleague.com/api/entry/$team_id/event/29/picks/";
        $sql = "INSERT INTO ..."
        // rest of code...
    }


}

You can now call the function like this: insert_team_data(1, 2, 3, 4, 5)

Upvotes: 2

Related Questions