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". So after it checks all the variables, it would change $TestData4 to "N/A".
i used echo to demo the syntax, you can use what you like
$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;
}
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.
Use the two-dollar sign.
See PHP variable variables: http://php.net/manual/en/language.variables.variable.php
foreach ($TestArray as $Data):
$VariableToTestConnditions=$$Data;
endforeach;