开发者

Extracting array with a suffix

开发者 https://www.devze.com 2023-03-13 16:25 出处:网络
Generally, we can extract an array, and also add an prefix to it, like this extract($array, EXTR_PREFIX_ALL, \"myprefix\");

Generally, we can extract an array, and also add an prefix to it, like this

extract($array, EXTR_PREFIX_ALL, "myprefix");
// which will give me output like $myprefix_myarrayvar

But, instead, is there a way to set a suffix instead of prefix? Something like,

$myar开发者_如何学编程rayvar_mypostfix;


First of all, you should never use extract because it can make it very hard to tell where some variables are coming from, never mind possible collisions. You don't save much with extract .. it's really just a tool of laziness.

Anyway, since you asked, no there does not seem to be a way to add a suffix with extract natively, so you would have to do it on your own:

foreach ($array as $key => $val) {
  ${"{$key}_suffix"} = $val;
}


There is no extract option for that. So you need a workaround. You could either write a boring foreach or prepare the keys prior extraction:

extract( array_combine(preg_replace('/$/', "_suffix", array_keys($array)), $array) );
0

精彩评论

暂无评论...
验证码 换一张
取 消