Jump to content

Simple "foreach" problem


davil

Recommended Posts

Ok so I'm getting into PHP and I have a decent sized MySQL/PHP database system working fine but I'm having problems with the foreach command...

 

When I get the info from a MySQL database I usually use the following command to assign a variable to each value:

 

foreach ($row as $key => $value) {$$key = $value;}

 

This works perfectly but I was wondering is there a way to check something like $datestamp vs $new_datestamp and $timestamp vs $new_timestamp by doing something like this code below?

 

foreach ($row as $key => $value) {
$$key = $value;
if ($new_$$key==$$key){echo "$new_$$key is same as old $$key, which is $value\n";
}

 

 

I know this doesn't work above but I'm presuming it's something to do with my syntax... I've had a look at PHP.net tutorials and done a bit of googling but I'm lost on this simplest of all problems...

 

I could do it the long way with like 20 conditions but I want to get more efficient in my programming.

Link to comment
Share on other sites

Why are you creating new variables to store values already in the $row array, just use them directly from the array. If you really want to do that, you can use the extract() instead of the "foreach" loop.

 

As to your other question, it would be much easier to just use the array values:

<?php
if ($new_timestamp == $row['timestamp'])
   echo '$new_timestamp is the same as $row[\'timestamp\'] ... ' . $row['timestamp'] . "\n";
?>

 

Ken

Link to comment
Share on other sites

Why are you creating new variables to store values already in the $row array, just use them directly from the array.

 

The reason for this is over 40 variables... I'm sorry I really should have mentioned there are loads of them. This is the reason I don't want to have an "If" condition for each one,  like in the code you just mentioned... as it seems a bit inefficient when I could do it properly using a foreach loop....

 

also I should mention I am using the following code to create the $new_timestamp etc. variables,

[edit]well not this exact code, but this kind of idea: instead of using $_REQUEST I'm actually splitting the data  from PATH_INFO but it's the same sort of deal[/edit]

$new_timestamp=$_REQUEST['timestamp'];
$new_datestamp=$_REQUEST['datestamp'];

etc. etc.

 

and then pulling out the old timestamp and old datestamp etc. etc. from the SQL database and I want to check each one against their older counterpart if you get me.... and I don't want to have to write a seperate "IF" statement for each variable ... especially seeing as I already have over 40 variables and it is likely I will add even more in the future.

 

If it is impossible to do it any other way I will use seperate "if" conditions but otherwise I'd like to know how to do this properly.

 

Thanks

 

oh just as a matter of interest here's the full code:

 

<pre>
<?php
require ("..\config.php");


$repl="$-$$";
$spr="*";
$data = explode($repl,$HTTP_SERVER_VARS['PATH_INFO']);


$new_datestamp = $data[1];
$new_datestamp=str_replace($repl, "/", $new_datestamp);
$new_timestamp = str_replace($spr," ", $data[2]);
$new_hostname = str_replace($spr," ", $data[3]);
$new_serial1 = str_replace($spr," ", $data[4]);
$new_serial2 = str_replace($spr," ", $data[5]);
$new_serial3 = str_replace($spr," ", $data[6]);  $serial3 = str_replace(".","", $serial3);
$new_primaryip = str_replace($spr," ", $data[7]);
$new_primarymac = str_replace($spr," ", $data[8]);
$new_lastuser = str_replace($spr," ", $data[9]);
$new_make = str_replace($spr," ", $data[10]);
$new_model = str_replace($spr," ", $data[11]);
$new_chassis_type = str_replace($spr," ", $data[12]);
$new_cpu_info = str_replace($spr," ", $data[13]);
$new_cpu_info2 = str_replace($spr," ", $data[14]);
$new_hdd = str_replace($spr," ", $data[15]);
$new_optical = str_replace($spr," ", $data[16]);
$new_ram = str_replace($spr," ", $data[17]);
$new_os = str_replace($spr," ", $data[18]);
$new_sp = str_replace($spr," ", $data[19]);
$new_iever = str_replace($spr," ", $data[20]);
$new_av = str_replace($spr," ", $data[21]);
$new_avver = str_replace($spr," ", $data[22]);
$new_avdat = str_replace($spr," ", $data[23]);
$new_monitor = str_replace($spr," ", $data[24]);
$new_chipset = str_replace($spr," ", $data[25]);
$new_audio = str_replace($spr," ", $data[26]);
$new_cproxy = str_replace($spr," ", $data[27]);
$new_lproxy = str_replace($spr," ", $data[28]);

$sqlone = "SELECT * FROM `aidahardware` where `hostname` = '$new_hostname' LIMIT 1";
$result = mysql_query($sqlone) or die(mysql_error());
$row = mysql_fetch_array($result);

foreach ($row as $key => $value) {
$$key = $value;
if ($new_$$key==$$key){echo "$new_$$key is equal to $$key\n";
}
?>
}

Link to comment
Share on other sites

I would use an array to old the "new" values, with the keys being your current names, then it becomes very easy to compare the "new" values to those in the database:

<?php
$new = array();
$fields = array('','datestamp','timestamp','hostname','serial1','serial2','serial3','primaryip','primarymac','lastuser','make','model',
                      'chassis_type','cpu_info','cpu_info2','hdd','optical','ram','os','sp','iever','av','avver','avdat','monitor','chipset','audio',
                      'cproxy','lproxy');
$data = explode($repl,$_SERVER['PATH_INFO']);
$new['datestamp'] = $data[1];
$new['datestamp']=str_replace($repl, "/", $new['datestamp']);
for ($i=2;$i<count($fields);$i++)
    $new[$fields[$i]] = str_replace($spr,' ',$data[$i]);
$new['serial3'] = str_replace(".","", $new['serial3']);
$sqlone = "SELECT * FROM `aidahardware` where `hostname` = '" . $new['hostname'] . "' LIMIT 1";
$result = mysql_query($sqlone) or die("Problem with the query: $sqlone<br>" . mysql_error());
$row = mysql_fetch_assoc($result);

foreach ($fields as $dmy => $fld) {
     if ($fld != '' && $new[$fld] == $row[$fld]
        echo '$new[' . $fld . '] is equal to $row[' . $fld . '], value: ' . $row[$fld] . "\n";
}?>

 

BTW, I don't think this line

<?php
$new['datestamp']=str_replace($repl, "/", $new['datestamp']);
?>

is going to do anything, since you've already exploded on the string in $repl and it won't be in the assigned value. Do you want:

<?php
$new['datestamp']=str_replace($spl, "/", $new['datestamp']);
?>

 

Ken

Link to comment
Share on other sites

Thanks for your code kenrbnsn it really helped me through a tight spot... I modified it a bit to suit my needs and here is the final code. I can't believe I never thought of using arrays like that.... I really have a lot to learn about program design... I'd love to go to college to study computer science but I can't afford it. ah well. maybe next year...

 

anyway here's the final code more or less.... I will be adding a lot of bells and whistles but it does what I need it for the minute so here goes:

 

<pre>
<?php
require("..\config.php");
$repl="$-$$";
$spr="*";

$data = explode($repl,$HTTP_SERVER_VARS['PATH_INFO']);

$new = array();
$fields = array('','datestamp','timestamp','hostname','serial1','serial2','serial3','primaryip','primarymac','lastuser','make','model',
                      'chassis_type','cpu_info','cpu_info2','hdd','optical','ram','os','sp','iever','av','avver','avdat','monitor','chipset','audio',
                      'currproxy','lanproxy');

//   I want the program to only watch these fields for changes.. I will program that
//   in later - I could have done all this with IF but I knew that this would change
//   dynamically and I wanted the program to be more versatile.
$watchedfields = array ('ram','primarymac','serial1','serial2','serial3');

//remove MB from amount of ram, i.e. 1024*MB becomes simply 1024
$data[17] = str_replace('*MB','',$data[17]);

//remove periods from serial3
$new['serial3'] = str_replace(".","", $new['serial3']);

$new['datestamp'] = $data[1];
//leave this for now as it is another thing entirely that's not too important to what I'm doing currently
//$new['datestamp']=str_replace($repl, "/", $new['datestamp']);


for ($i=2;$i<count($fields);$i++)
    $new[$fields[$i]] = str_replace($spr,' ',$data[$i]);

$sqlone = "SELECT * FROM `aidahardware` where `hostname` = '" . $new['hostname'] . "' LIMIT 1";
$result = mysql_query($sqlone) or die("Problem with the query: $sqlone<br>" . mysql_error());
$row = mysql_fetch_assoc($result);

foreach ($fields as $dmy => $fld) {
     if ($new[$fld] != $row[$fld])
     {echo $fld." has changed,old value: [" . $row[$fld] . "] new value: [" . $new[$fld]. "]\n";}
}


?>

Link to comment
Share on other sites

Just as a final note: you can't name variables with anything other than numbers, letters and underscores. So $my$v$a$r would not work.

 

Also: don't use $$variables unless you can't avoid it. Not only is it inefficient (makes loads of variables with no categorization at all - that's why they invented arrays ;) ) but it also makes coding harder to understand.

 

Use the 'topic solved' button - it's there for a reason! :)

Link to comment
Share on other sites

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.