Foreach $_POST

Discussion in 'PHP' started by adamjblakey, Jun 12, 2009.

  1. #1
    Hi,

    I have several fields in my form which i want to loop through. I want to add them all to a variable separated by a : but there is one field i do not want to be added which is called red.

    So need something like this but how would i stop it adding the field called red?

    
    $new .= $_GET['id'];
    							
    				foreach($_POST as $post) {
                    	$new .= .":".$_POST[$post];
    				}
    				
    				$new .= .',';
    
    PHP:
    Also do you notice anything incorrect with the above as this does not work and just goes to a blank page.

    Cheers,
    Adam
     
    adamjblakey, Jun 12, 2009 IP
  2. Dennis M.

    Dennis M. Active Member

    Messages:
    119
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    58
    #2
    I'm not sure what your sending through your post (if it's an array or what have you) but try this:

    $new .= $_GET['id'];
                                
                    foreach($_POST as $post => $val) {
                        $new .= ":".$val.",";
                    }
                    
    PHP:
    Regards,
    Dennis M.
     
    Dennis M., Jun 12, 2009 IP
  3. CreativeClans

    CreativeClans Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    To exclude a field called red:
    
    $new .= $_GET['id'];
                              
    foreach ($_POST as $post => $val) {
      if ($post != 'red') {
        $new .= ':' . $val;
      }
    }
    
    $new .= ',';
    
    PHP:
     
    CreativeClans, Jun 12, 2009 IP
  4. clarky_y2k3

    clarky_y2k3 Well-Known Member

    Messages:
    114
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    108
    #4
    It would be better to simply do this before entering the foreach:-
    unset($_POST['red']);
    PHP:
    This is more efficient and saves a test/comparison for each element. Removing the 'red' field is now of O(1) rather than O(n).
     
    clarky_y2k3, Jun 12, 2009 IP
  5. CreativeClans

    CreativeClans Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    True. Admitted that he won't need it later on.
    Of course, if that's the case, he might just save it in a variable, and then delete it from the $_POST array.
     
    CreativeClans, Jun 12, 2009 IP