Timps
Timps

Reputation: 58

PHP fill array based on var

I feel like I'm struggling to find the answer here because I think I'm missing some key piece of info.

What I am trying to do is run a loop over some data, and then do something different with it based on one of it's values.

So the print_r of the data I am looping over gives me this. This is all good, it has only the data I need, nothing excess.

Array
(
[foodid] => 1
[menuid] => 1789798798
[creatorid] => 1
[foodtype] => hotdog
[frequency] => weekly
[cost] => 20
[chargedate] => 2017-07-14 11:05:18
)

And I want to do SOMETHING to it, depending on the value in frequency. The things I want to do are all stored in a set of identical arrays.

weekly, 2weekly, monthly, daily. eg

$_weekly = array(
"cost" => "2",
"order" => "5",
"years" => "0",
);

$_2weekly = array(
"cost" => "4",
"order" => "10",
"years" => "0",
);

Similar arrays for weekly 2weekly etc.

It seems simple to just use a var like $workingvar in the loop. So when I get there I can just use $workingvar = $_weekly, or $workingvar = $_2weekly.

So, how can I set the contents of $workingvar to be one of those existing arrays? Then I can use the same loop/function on each row in the data, and change the values it pulls in, depending on what that frequency value contains.

Edit added second array example.

Upvotes: 1

Views: 51

Answers (2)

Aurel Bílý
Aurel Bílý

Reputation: 7973

There are many ways to achieve this. If you can guarantee frequency to always have a valid value, then a global look-up array like this could do:

// Define your $_weekly, $_2weekly, etc here

$freqLookup = array(
    "weekly" => $_weekly,
    "2weekly" => $_2weekly,
    // et cetera
  );

Then in your code you simply assign to $workingvar:

$workingvar = $freqLookup[$data["frequency"]];

If you cannot guarantee frequency to always have a valid value, then you can check that the key exists first:

if (!isset($freqLookup[$data["frequency"]])) {
  // Throw an exception or do something to handle the error
}

A possible alternative (but less elegant) solution is a switch, and even less elegant is an if ... else if ... else chain. They could have their merits if you needed to do something very different for each case.

Edit: u_mulder's answer is probably even better IF you can guarantee the sanity of your data. If you are accepting user data, it could be dangerous. Another advantage to a lookup array is that you could map keys to different variables, e.g. "2weekly" => $_biweekly

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

So you need variable variable, in your case it is:

$arr['frequency'] = 'weekly';
$_weekly = [11,22,33];

$workingvar = ${'_' . $arr['frequency']};
var_dump($workingvar);

But having array with same keys is a more preferred solution (simply because it's more readable and shorter):

$arr['frequency'] = 'weekly';
$arrs = [
    'weekly' => [11,22,33],
];
var_dump($arrs[$arr['frequency']]);

Upvotes: 2

Related Questions