简体   繁体   English

在数组中存储变量名

[英]Storing Variable Names in an Array

So I have a List of Variables 所以我有一个变量列表

$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";

I want to make a function that will run all these variables through a filter. 我想制作一个将通过过滤器运行所有这些变量的函数。 I want to make this a loop that checks all the variables in one shot. 我想使它成为一个循环,一次检查所有变量。 I had the idea of storing the variable names in an array. 我有将变量名存储在数组中的想法。 This is shown below. 如下所示。

$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");

So my main question is how would I take these names in the array and run a loop that checks to see if a certain condition is met. 因此,我的主要问题是如何将这些名称放入数组中并运行一个循环,以检查是否满足特定条件。 Example below. 下面的例子。

foreach ($TestArray as $Data):

   $VariableToTestConnditions="$".$Data;



endforeach;

I know that statement doesn't work, but it is all I could think of. 我知道这种说法是行不通的,但这就是我能想到的。 The out come of this would be if the variable value =="Yes" then is would change the original variable's value to "N/A". 结果就是,如果变量值==“ Yes”,那么它将原始变量的值更改为“ N / A”。 So after it checks all the variables, it would change $TestData4 to "N/A". 因此,在检查完所有变量后,会将$ TestData4更改为“ N / A”。

instead of having an array of the names, it would make more sense to have an associative array (key value pairs): 代替使用名称数组,使用关联数组(键值对)会更有意义:

$TestArray = array(
    "TestData1" => "Hello",
    "TestData2" => "",
    "TestData3" => "0",
    "TestData4" => "Yes",
    "TestData5" => " ",
    "TestData6" => "No"
);

now if you wanted to test a variable: 现在,如果您想测试变量:

foreach($TestArray as $key => $value) {
    if($VariableToTestConnditions == $value) {
        //do something 
    }
}

if you wanted to change the value of a testdata: 如果要更改测试数据的值:

$TestArray["TestData1"] = "Good Bye";

this way is much neater and simpler. 这样更加整洁和简单。

i used echo to demo the syntax, you can use what you like 我用echo演示了语法,您可以使用喜欢的东西

$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";

$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");


foreach($TestArray as $a){

echo ${$a};
 //or 
echo $$a;

}

Use the two-dollar sign. 使用两美元的符号。

See PHP variable variables: http://php.net/manual/en/language.variables.variable.php 请参阅PHP变量变量: http : //php.net/manual/zh/language.variables.variable.php

foreach ($TestArray as $Data):

   $VariableToTestConnditions=$$Data;

endforeach;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM