从数组列表创建变量名 [英] creating variable names from an array list

查看:85
本文介绍了从数组列表创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态地创建基于阵列上的变量名?我的意思是我想循环遍历这个数组有一个foreach,并创建一个新的变量 $ elem1 $其他等这可能吗?

  $ myArray的=阵列(elem1,其他,elemother','是以lastElement');
的foreach($ myarray中的编曲$){
    //创建一个新的变量名为$ elem1(或其他$或者$ elemother等)
    //并为其分配一些缺省值1
}


解决方案

 的foreach($ myarray中为$名){
   $$名= 1;
}

<击>这将创建变量,但他们只是在的foreach 循环中可见。感谢扬Hančič指出了这一点。

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?

$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
    //create a new variable called $elem1 (or $other or $elemother, etc.) 
    //and assign it some default value 1
}

解决方案

foreach ($myarray as $name) {
   $$name = 1;
}

This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.

这篇关于从数组列表创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆