Hi,
So far I know how to create a session variable (eg, where name="bob") and then pass that variable onto other pages.

But does anyone know how to create an session array (whereby I could have names equal to "Bob", "Harry", "Sally" and indeed any other name variables that may be added)?????

I've checked 3 books and the PHP manual on this one and so far I don't think any of them explain this one very well.

I'm just trying to find out how to do this in its absolute most simple form.

Thanks

    $SESSION['name'][1]="Bob";
    $
    SESSION['name'][2]="Harry";

      Just register the array ...

      $firstNames = array('Bob', 'Elvis');
      $surNames = array('Marley', 'Presley');
      $fullNames = array($firstNames, $surNames);
      session_register('firstNames', 'surNames', 'fullNames');
      

        Thanks, but none of those replies have solved my problem.

        With the first method (from scoppc), I need to literally spell out each individual variable using square brackets with a number inside. Eg,

         $_SESSION['name'][1]="Bob";   

        ...and for every new variable I need to declare a new $_SESSION varialbe with a new number inside the curly brackets.

        This is no use because ultimately I'm hoping to give users the choice of adding new variables to the session array via a simple form. So, one user may only add one new variable but another user may add a hundred new variables.

        So, I need the session array to be flexable and expandable.

        Thanks anyway.

        The second reply from steadyguy was pretty good also, but unfortunately it falls on two counts.

        Firstly, I'm using commands like....

         $_SESSION['name']="Bob";   

        ...throughout my script.

        I have read from several sources (including the PHP manual) that it's bad practice to mix "session_register()" and "$_SESSION[]" commands in the same script.

        As well as that, I'm not entirely sure how I could retrieve the information from your script. I've already made a few attempts at printing out the session arrays from your code, but instead of getting the script to print out "Bob Marley... etc", the best I can get is for the script to simply display the word "Array" on the screen.

        Perhaps I should have stressed in my original question that I would appreciate it if someone could furnish me with a procedure for retrieving the session arrays.

        Thanks anyway guys. I live in hope.

          Think about it a little bit:

          Step 1) Create the array of user requested session variables like this.

          //assuming this is inside the section where you're processing the
          //form input
          
          //set up an array with the form variables you don't want to 
          //process. i.e. the button variable
          $dontUse = array('name1','name2','etc');
          $myVars = array();
          foreach(array_keys($_POST) as $curInput) {
            //skip processing of specified keys
            if(!in_array($curInput,$dontUse)) {
              //figure out which ones to the user wants, this assumes they
              //are checkboxes with a value of 1
              if($_POST[$curInput]) {array_push($myVars,$curInput);}
            } //end if
          } //end foreach
          
          //at this point $myVars is an array that holds all the variables the
          //user wants to put into session variables. Now we can create the
          //session array as posted above
          
          //start the session
          session_start();
          
          //start building the array
          foreach($myVars as $curVar) {
            $_SESSION['UserSelected'][$curVar] = $$curVar;
          } //end foreach
          
          //close and write the session
          session_write_close();
          

          This could be done much more efficiently with a single foreach loop but I broke it out this way to demonstrate what I'm doing more clearly. I would recommend making it a single foreach loop before implementation. No I'm not goint to do that for you.

          Edit: fixed error.

            If that's a serious attempt to explain how to create and view session arrays in their most simple format, then all I can say is you must be a textbook example of an AMAZING programmer.

              First off ... to get useful information about an array easily, use print_r($arrayName);

              Also, assuming the bit of code I supplied above, you can simply use use the variable you registered. Ie.,

              print_r($fullNames);
              

              Which will output:

              Array
              (
                  [0] => Array
                  (
                      [0] => Bob
                      [1] => Elvis
                   )

                  [1] => Array
                  (
                      [0] => Marley
                      [1] => Presley
                   )
              )

              Or if you want something that's a bit more userfriendly:

              print '<ul>';
              foreach ($firstNames as $name) {
                  print "<li>$name </li>";
              }
              print '</ul>';
              

              In a situation such as this, an associative array is admittedly much more convenient - but in some ways, it is also less flexible.

              The reason I use session_register() instead of $_SESSION, is because I built the arrays myself. I assumed you do the same thing with submitted information. There's nothing wrong with session_register(); the warning in the PHP manual is to not use it if you have register_globals set to 'on', because it implicitly trusts user supplied data, and then possibility of registering something nasty becomes quite high. Validate it first, rejecting everything that's not acceptable (ie., punctuation, numbers, stuff that looks like HTML), and then you can pack it into arrays, register it, do whatever you want, really.

              In addition, If you have $SESSION['name'] = 'Bob', you can use extract($SESSION);, to get $name = 'Bob' ... in my own experience, this is much easier to type, and probably easier to read. But like I said above, if you use session_register() ... you can just access the variable directly - without using extract()

                Originally posted by Davidc316
                If that's a serious attempt to explain how to create and view session arrays in their most simple format, then all I can say is you must be a textbook example of an AMAZING programmer.

                I wrote something that explains how to do what the poster said he wanted to accomplish in his last post. But I don't think that code is all that complex.

                  If I can just address drawmack first-

                  Listen... I think you're probably right and I have no doubt that your code is not only clean but easy to read and simple. It just so happens that I've been wrestling with this sessions array stuff since last Friday and my brain seems to have turned into jelly.

                  My worst nightmare today has been the idea of someone posting a large paragraph of code and saying "read that". Normally, I'd be totally happy with the idea, but right now if then my head is in danger of falling clean off!

                  My little remark about "You must be a great programmer" (or whatever I said) was just a passing attempt at a little joke that used to be circulate amongst English Lit students at the Uni (mainly the implication was that people who are good at science/mathematical subjects are not so good at communication and language tasks.

                  Anyway, it was totally unfunny and uncalled for and I think it's safe to say that this is probably the wrong crowd for that kind of humour. In any case, I just want you to know that I AM very grateful for your post!

                  If I haven't solved this session stuff by tonight, then I shall go through every line of your code with a fine tooth comb.

                  Thanks


                  Steadyguy- I'm working like a dog here and the stuff that you're saying is absolutely fitting in with the experiences I'm having.

                  I don't want to start celebrating yet but I think I'm well on the road to getting the session stuff nailed. Thanks to you for that!

                  I'm just gonna play around with my little test scripts for a wee while more before I mark this one as resolved.

                  Cheers!

                    David,
                    If you look closely at my code it's mostly comments only really 10 lines of code.

                      I know. What can I say? I AM a looney of the first division.

                      Anway,

                      I seem to be on the road to getting this one solved.

                      Thanks to you guys;

                      I finally know how to create a session variable which is an array.

                      I also know how to pass that array session variable from page to page.

                      And finally, I know how to display the information that's contained within the array session variable.

                      There is just one more thing that I'm not sure about (well, there's actually 2 more things, but I'll ignore the second problem just now cos I don't want to go into a state of overwhelm).

                      Ok, here's the vibe....

                      Let's say we have an array variable called "names" (or something) which contains the information "Tom", "Dick" and "Harry".

                      Ok, now thanks to this thread. I know how to create that array session variable and to view it. Horary to that!

                      BUT, what if I wanted to add a new name to the list?

                      So far, I have the array defined as being "tom", "dick" and $new. And on the page that defines the variables I have $new declared as being equal to "Harry". HENCE, when I view my session variable array I get Tom, Dick and Harry printed onto the screen.

                      That's cool.

                      But if I later change the variable of $new to (say) "David", then instead of getting "Tom, Dick Harry and David", I am getting "Tom, Dick and David".

                      So, in other words it's just replacing the value that was already there- not adding a new one.

                      Right now I'm just trying to work out how to change the variable of $new and have it adding a NEW thing to the list (as opposed to modifying a value on the list).

                      That's my problem and I wouldn't blame you if you never responded. Thanks anyway!

                        Look at my code. I loop through the input variables and set up an array that contains just the necessary variables so if the user adds a variable it is added to the array

                          To add an element to the end of the array:

                          $names = array('Harry', 'Tom', 'Dick');
                          $names[] = 'David';
                          

                          You can do this as much as you like.

                          To assign a string of names to $new from the array, if you don't know how many names are in it:

                          foreach ($names as $name) {
                              if ($new)
                                  $new .= ", $name";
                              else
                          
                               $new = "$name";
                          }
                          

                          This will give you a comma separated list of all the names in the array.

                          If you need to do this repeatedly, and on demand, create a function ...

                          function nameList($array) {
                              foreach ($array as $name) {
                                  //the rest is the same as above
                              }
                          }
                          

                          ... then pass it the array that you need converted into a list. Note that the variable $new won't be accessible outside the function so you could either global it, or you can return. An even more flexible option is OOP, but that's a whole 'nuther ball 'o wax.

                            Steady,
                            I've been playing with your little snippet of code for over an hour, but every time, it merely gives one of the variables a new value. It does not increase the size of the array.
                            I'm refering to the bit that goes...

                            foreach ($names as $name) {
                            if ($new)
                            $new .= ", $name";
                            else

                                 $new = "$name"; 

                            }

                            All I can think of is to paste what I've done so far and demonstrate that I am indeed trying out the things that you've been advising.

                              Two things to do. First: create an array. The fact that it's going to be a sessioned array is irrelevant. It's an array. You know how to manipulate arrays? Plenty of examples given
                              $myarray = array('This', 'That', 'The other');
                              print_r($myarray);
                              $myarray[] = 'Yet another';
                              print_r($myarray);

                              and all the other things that can be done with arrays, simple and complex.

                              Second part. You want that to be a session. Okay, that's just a matter of giving it the right name. Instead of $myarray it's $_SESSION['myarray'].

                              That's the only difference.

                              You can use $_SESSION['myarray'] everwhere you could use $myarray and for everything you could use $myarray for. You can add elements to it, remove elements from it, sort it, reverse it, slice it, merge it, whatever. You can even replace its contents with another array entirely in exactly the same way you would assign a new value to any other variable.

                              $_SESSION['myarray'] = $anotherarray.

                              The fact that it manages to magically have the same value in another script has no effect on its behaviour in this script. The fact that your array happens to be an element in another (called $_SESSION) is also no sudden conceptual roadblock.

                                David ... Sorry if I didn't explain myself very well ...

                                To add values to an array, you need to use the first snippet I noted above: $arrayName[] = 'next value'; That's all. This will add a new element onto the end of any array, and assign it the value you gave - 'next value' in this example. It will never overwrite the last element of an array, unless you're passing it a key as well ($arrayName[2] = 'overwritten'; (Bye, Harray!).)

                                The bit that you quoted in your last message actually creates a new variable ($new) if it doesn't already exist. $new is of type String (as opposed to Array), and contains a comma-separated concatenation of all the names that were in whatever array was looped through. If $new existed before the execution of the foreach, then it will tack the names onto the end of that string. If it already exists, but it's not a string, PHP will try to convert the existing value to type Sting. For example, 3.14 would become '3.14', and an Array will become 'Array'), then tack on the names, and $new would have a value something like 'Array, Tom, Dick, Harry'.

                                Does that make a bit more sense?

                                  I think I understand what you're saying and yes, there is no denying that the [] trick does indeed add a new variable onto the array.

                                  But the trouble is, if I make subsequent visits to the page or if I link the array to other pages and then CHANGE the variable of $new on each occassion then it does not add yet another variable to the end of the string- it merely gives $new a new value.

                                    I mean... I don't want to start talking too deeply about forms and sessions at this point because as the last guy who posted said- this is strictly an array problem and if I can figure out what's going on with arrays, then I can just convert all of the data into a session variable.

                                    But if I can briefly mention forms...

                                    You've got to realise that the end goal for me is to be able to create a form in which a user types in something and hits submit.

                                    Now, whatever the user submits will be given a variable name like $new (for example). IF the users types in something on the form and hits submit, I would like it to add that variable onto an array. Furthermore, if the person reloads the webpage (or visits the page a minute or two later) then I would like the user to be able to fill out the same form and submit again. BUT, instead of it just reassigning a new value to $new, I'd like it to add YET ANOTHER new variable onto the array (so this means that the array would still contain the old variable of new as well as the new, recently submitted variable of new).

                                    So, your solution is pretty good. It comes close and it does indeed produce an entirely new variable for the array. Thank you for giving me such a good run for my money!

                                    BUT, the problem is, when the form is resubmitted or when the value of $new is somehow changed, then it just changes the value of $new. It does not create ANOTHER new variable.

                                      Then perhaps what you want to do is make $new an array, and then add the String version as an element into that array.

                                      foreach ($names as $name) {
                                          if ($new)
                                              $nameString .= ", $name";
                                          else
                                               $nameString = "$name";
                                      }
                                      $new[] = $nameString;
                                      session_register('new');
                                      

                                      Or am I misunderstanding you?

                                        I think I've finally nailed it!

                                        The key to this one was (funnily enough) in the code that Drawback posted yesterday.

                                        At the time, I didn't have the energy to go through it, but this afternoon I had a closer look at his code and I noticed a sneaky little command in there called "array_push". THAT'S THE KEY!!!

                                        Till now, nobody has ever really sat me down and explained "array_push" to me. I've got three pretty thick PHP books here in my flat with me and "array_push" doesn't seem to get a mention in any of them!!!

                                        So, I was totally unaware of the existence of the array_push function.

                                        Now that I've finally pinpointed what the function does, the world seems like a better place. What's more, I now realise that all the programming in the world probably would not have solved this one UNLESS there was an array_push in there at some point.

                                        Ok. All is well. I'm just gonna fiddle around with my testscripts for a while and then I'll hopefully come back and mark this one as resolved!

                                        Thanks!

                                          Write a Reply...