I have the following PHP function:
public function createOptions($options, $cfg=array()) {
$cfg['methodKey'] = isset($cfg['methodKey']) ? $cfg['methodKey'] : 'getId';
$cfg['methodValue'] = isset($cfg['methodValue']) ? $cfg['methodValue'] : 'getName';
$cfg['beforeKey'] = isset($cfg['beforeKey']) ? $cfg['beforeKey'] : '';
$cfg['beforeValue'] = isset($cfg['beforeValue']) ? $cfg['beforeValue'] : '';
$cfg['afterKey'] = isset($cfg['afterKey']) ? $cfg['afterKey'] : '';
$cfg['afterValue'] = isset($cfg['afterValue']) ? $cfg['afterValue'] : '';
$array = array();
foreach ($options as $obj) {
$array[$cfg['beforeKey'] . $obj->$cfg['methodKey']() . $cfg['afterKey']] = $cfg['beforeValue'] . $obj->$cfg['methodValue']() . $cfg['afterValue'];
}
return $array;
}
It’s something I use around my app to create select boxes from array data. I just recently added 4 new $cfg variables for adding strings before or after the key and value of the select box. So for example, if my drop down list looked like “A, B, C” by default, I can pass:
$cfg['beforeValue'] = 'Select ';
$cfg['afterValue'] = ' now!';
and get “Select A now!, Select B now!, Select C now!”
So this works fine, but I was wondering if there was some way in PHP to accomplish this in one line sorta speak rather than two. I figure there must be a special way to do this.
First, simplify that horrendous code with this:
No need for all the
issetand repeated key names, a simple array union will do.Secondly, you can use something like
sprintf: