NYCPHP Meetup

NYPHP.org

[nycphp-talk] accessing $_SESSION elements

Robert Redcay rob at nyc.yamaha.com
Fri Oct 24 19:22:07 EDT 2003


Aaron, I still think that arrays would do it. See my comments inline, 
and also play with code snidbit at the bottom of my post.

Aaron Fischer wrote:

> Hi Robert,
>
> I do have an array of data, let me backtrack to explain:
> In the first form a user enters name, etc. and how many fairs they 
> want to enter.
> On post, a loop iterates set number of times which is equal to the 
> number of fairs they have chosen.
> On each iteration, the loop spits out the html form fields that 
> enables the user to enter each fair, i.e. 1_fair_name, 
> 1_fair_location, 1_fair_date, 2_fair_name, 2_fair_location, 
> 2_fair_date, etc.  The 1, 2, 3, etc. distinguish each fair.  If I was 
> creating a static html form I would be naming the fields with the same 
> convention.  Here I am just using php to create the fields.

See code below.

> I did this to make the interface more appealing, so the user doesn't 
> have to wade through a long form with all of the fields for 10 
> different fairs if they only want to enter 1.

makes sense.

>
> Then on submit I am looping the set number of times again and testing 
> to see if the array elements are empty.  If any element is empty I 
> will reload the form with appropriate error messages.

now you just need foreach()

> On typing this I realize that I don't need to test to see if array 
> elements are there.  I know what is there, based on the number of 
> fairs they have chosen, which is stored as an array element as well.  
> I just want to test to see if said fair elements are empty.

exactly, which is what Micheal was trying to get you to realize in his 
post which pointed you to the phundamentals page.

> I have been reading through the array functions but hadn't found a 
> good way to say "Does array key "foo" exist?  and if it does, is it 
> empty?".  I could very well be blind at this point.

In general, to answer the question "does a variable exist, and if it 
does, is it empty," all one needs is a call to the empty() function.
In your case, you need an additional call to the function 
array_key_exists(), but again, in this case you know the key exists, the 
only question is is it empty?


/* -------- example code --------- */
<?
error_reporting (E_ALL);

if (isset ($_POST['fairs'])) {
  echo "<pre>\n";
  print_r ($_POST['fairs']);
  echo "</pre>\n";
}
?>

<form action='' method="POST">

Fair 1: name:     <input type="text" name="fairs[1]['name']"><br />
Fair 1: location: <input type="text" name="fairs[1]['loc']"><br />
Fair 2: name:     <input type="text" name="fairs[2]['name']"><br />
Fair 2: loc:      <input type="text" name="fairs[2]['loc']"><br />

<br />
<input type=submit value="Go">
</form>

/* -------        -------- */

Hope this helps,
Robert Redcay




More information about the talk mailing list