[thelist] need guidance on arrays and loops in PHP

Ken Snyder kendsnyder at gmail.com
Thu Mar 27 14:40:17 CDT 2008

Jeremy Weiss wrote:
> I have to write a script to process some values that could have been
> submitted via several different forms. One of the values, has the
> potiential to be an array. If that value is there, then it's going to
> be a number that  happens to be a primary key for a table in a MySQL
> db. Up to this point, things seem fairly simple. But the record that
> key goes to will be something like:
> id (pk) | lo_id (fk) | la_id (fk) | bla bla bla 30+ other fields
> If it's just one value in the array, then there's no problem. But if
> it's more than one, then I have to pull the lo_id and la_id fields and
> IF those match for each value in the array, then I'll do one thing.
> However, if even one of the values doesn't match then I do something
> totally different.
> So I'm thinking a simple  foreach (array_expression as $value)
> would let me loop through and run the SELECT statements to pull the
> values of lo_id and la_id for each key in the array. But where do I
> store them  (the values of lo_id and la_id) so that I can compare them
> to what is turned up on the other searches? Or, do I just run through
> on the first one, and then make the comparisons in the foreach loop?
> -jeremy

Boy that's confusing.  So assuming you're post vars are named the same 
as your table columns, are you saying that you have three post vars: id, 
lo_id, and la_id that are all arrays?  Maybe pasting some code would be 

Without totally understanding, I think these two points might be helpful:

1. You can receive multi-dimensional post values:
<input ... name="record[1][lo_id]" value="lo_id value for id=1" />
<input ... name="record[1][la_id]" value="la_id value for id=1" />
<input ... name="record[2][lo_id]" value="lo_id value for id=2" />
<input ... name="record[2][la_id]" value="la_id value for id=2" />
Then $_POST["record"] would be equivalent to something like this:
  "1" => array("lo_id" => "lo_id value for id=1", "la_id" => "la_id 
value for id=1"),
  "2" => array("lo_id" => "lo_id value for id=2", "la_id" => "la_id 
value for id=2")

2. You can save the results of the query you use for the display into 
$_SESSION so that you can make comparisons after post without requerying.

3. Be sure to scrub and validate so that you don't insert table records 
for ids that the user should not have access to.

- Ken Snyder

More information about the thelist mailing list