Reputation: 866
i wondering how i can make it simpler... the thing is
if($results['experience'] == 0) { loadViev('experience',$experience, $careerGoals,$mainSectionLines); }
if($results['Education'] == 0) { loadViev('Education',$graduate,$careerGoals,$mainSectionLines); }
if($results['Extra'] == 0) { loadViev('Extra',$extra,$careerGoals,$mainSectionLines); }
if($results['Licence'] == 0) { loadViev('Licence',$licence,$careerGoals,$mainSectionLines); }
if($results['Cert'] == 0) { loadViev('Certyfikaty',$cert,$careerGoals,$mainSectionLines); }
if($results['conferences'] == 0){ loadViev('Conferences',$conferences,$careerGoals,$mainSectionLines); }
if($results['Courses'] == 0) { loadViev('Courses',$Courses,$careerGoals,$mainSectionLines); }
if($results['Hobbys'] == 0) { loadViev('Hobby',$hobby,$careerGoals,$mainSectionLines); }
As you can see, if some "name" == 0
function will run, there is for now around 14 combination, i know there is possible to do it faster than copy and paste whole code 14 times...
result code:
$results =[];
foreach ($userChoice as $key => $value) {
$setVal = $value['key'];
$results[$setVal] = $value['order'];
}
Result only grab name of a section and order nr.
'$userChoice
' is just a array with data
Do anybody have a idea how i can do it? Also the thing is result collect all the section data (14 section) where as you can see i need only selected 8.
Upvotes: 0
Views: 128
Reputation: 42304
The only difference is the word being loaded and the name of the variable. The word remains the same, but the variable is lowercase.
As such, all you would need to do is loadViev
the $setVal
name (the word itself) as the first argument, and $$setval
as the second. This executes the word as a variable, making use of variable variables.
Unfortunately you can't (easily) use something like strtolower()
on a variable variable directly, so you'll have to convert these to lowercase independently first.
This can be seen in the following:
$results =[];
foreach ($userChoice as $key => $value) {
$setVal = $value['key'];
$results[$setVal] = $value['order'];
if ($value['order'] == 0) {
$lower = strtolower($setVal);
loadViev($setVal, $$lower, $careerGoals, $mainSectionLines);
}
}
Upvotes: 2
Reputation: 4180
How about creating a structure holding relevant values and iterating over it?
$mapping = [
['key' => 'experience', 'view' => 'experience','data' => $experience],
['key' => 'Education', 'view' => 'Education','data' => $graduate],
['key' => 'Extra', 'view' => 'Extra','data' => $extra],
...
...
];
foreach ($mapping as $m)
{
if ($results[$m['key']]==0)
{
loadViev($m['view'], $m['data'], $careerGoals,$mainSectionLines);
break;
}
}
if you can make your key/variable names consistent, you could simplify the code even further. E.g.
$validKeys = ['experience', 'education', ... ];
foreach($validKeys as $k)
{
if($results[$k] == 0)
{
loadviev($k, $$k, $careerGoals,$mainSectionLines)
}
}
Upvotes: 1