sprntrcr Posted November 28, 2014 Share Posted November 28, 2014 Hi folks, Amateur coder here in need of some help. Background: I have a dozen sensors that get recorded in a database. The sensors are not very reliable, so to smooth out the data to graph, I compare the reading to the previous reading and if they differ by a given delta I replace the reading by the previous reading (smooth out spikes). The data for each sensor is loaded into arrays that are names according to sensor numbers (ie sensor one - $sensor1, sensor 6 - $sensor6). I have go through and do the comparison on each array and just repeat the code a dozen times, but I'd like to simplify the amount of code if possible. I'm not sure how to refer to an array by using a variable. Here is a simplified example of what I would like to do. The issue comes with - $array($i)[$x] Hope this makes sense of what I'm tring to do. Any guidence would be greatly appreciated. Trying to become a better programmer than just repeating the same piece of code a dozen times.. <?php //define arrays of data $array1 = array (7,8,9,10,11,12); $array4 = array (13,14,15,16,17,18); $array6 = array (1,2,3,4,5,6); //define array of sensors $sensors = array(1, 4, 6); //loop through each data point of each array foreach ($sensors as $i) { for ($x = 0; $x <= 6; $x++) { echo $array($i)[$x]; } } ?> Link to comment https://forums.phpfreaks.com/topic/292770-variables-in-array-name/ Share on other sites More sharing options...
ginerjm Posted November 28, 2014 Share Posted November 28, 2014 I think you are looking for 'variable variables'. Check the manual out here: http://php.net/manual/en/language.variables.variable.php Link to comment https://forums.phpfreaks.com/topic/292770-variables-in-array-name/#findComment-1497935 Share on other sites More sharing options...
mac_gyver Posted November 28, 2014 Share Posted November 28, 2014 you would just make your series of numbered variables into an array with an index being the sensor number - $array[1] = array (7,8,9,10,11,12); $array[4] = array (13,14,15,16,17,18); $array[6] = array (1,2,3,4,5,6); your echo statement, inside the looping code, would simply be - echo $array[$i][$x]; or you could simply loop over the data directly using foreach($array as $sub_array){...} Link to comment https://forums.phpfreaks.com/topic/292770-variables-in-array-name/#findComment-1497937 Share on other sites More sharing options...
sprntrcr Posted November 29, 2014 Author Share Posted November 29, 2014 Thanks, I was pulling my hair out trying to figure it out, and you guys set me straight and now I have it working....... Link to comment https://forums.phpfreaks.com/topic/292770-variables-in-array-name/#findComment-1497988 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.