Jump to content

foreach loop rewrite in less code


dsp77

Recommended Posts

hello, i have the piece of code that works but i'm wandering if there is a shorter way. Thanks

foreach ($decode as $value) {
if($value == 'A1') $tpl->setVariable('checked0','checked="checked"');
if($value == 'A') $tpl->setVariable('checked1','checked="checked"');
if($value == 'B') $tpl->setVariable('checked2','checked="checked"');
if($value == 'B1') $tpl->setVariable('checked3','checked="checked"');
if($value == 'BE') $tpl->setVariable('checked4','checked="checked"');
if($value == 'C') $tpl->setVariable('checked5','checked="checked"');
if($value == 'C1') $tpl->setVariable('checked6','checked="checked"');
if($value == 'CE') $tpl->setVariable('checked7','checked="checked"');
if($value == 'C1E') $tpl->setVariable('checked8','checked="checked"');
if($value == 'D') $tpl->setVariable('checked9','checked="checked"');
if($value == 'D1') $tpl->setVariable('checked10','checked="checked"');
if($value == 'DE') $tpl->setVariable('checked11','checked="checked"');
if($value == 'D1E') $tpl->setVariable('checked12','checked="checked"');
}

Link to comment
https://forums.phpfreaks.com/topic/243965-foreach-loop-rewrite-in-less-code/
Share on other sites

Untested, but I'm thinking along these lines:

$map = array_flip( array( 'A1', 'A', 'B', 'B1', 'BE', 'C', 'C1', 'CE', 'C1E', 'D', 'D1', 'DE', 'D1E') );
foreach ($decode as $value) {
$tpl->setVariable("checked$map[$value]", 'checked="checked"');
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.