Jump to content

Variables in array name?


Go to solution Solved by sprntrcr,

Recommended Posts

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

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){...}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.