Welcome to WebmasterWorld Guest from 54.158.25.146

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Writing an unpredictable number of variables into an Array

     
5:28 pm on Dec 11, 2012 (gmt 0)

Preferred Member from GB 

10+ Year Member Top Contributors Of The Month

joined:July 25, 2005
posts: 400
votes: 12


In normal circumstances if I have two variables, I can write them into an array like this

$var1 = 3;
$var2 = 4;
$myarray = array($var1, $var2);


What if I don't know in advance how many variables I will have? Variables are sent via form input from another script with method="POST". I can get 4 variables now but a few minutes later someone else might send 14 variables.

All I really need is to save the variables in an array.

Could you please point me in the right direction?
7:50 pm on Dec 11, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:May 6, 2008
posts:2011
votes: 0


foreach($_POST as $name => $value) {
print "$name : $value<br>";
}
1:56 pm on Dec 12, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 3, 2003
posts:1633
votes: 0


You can use [] to append to an array:


$myarray = array();
foreach($_POST as $k => $v)
{
$myarray[] = $v;
}
1:04 pm on Dec 15, 2012 (gmt 0)

Preferred Member from GB 

10+ Year Member Top Contributors Of The Month

joined:July 25, 2005
posts: 400
votes: 12


@dmorison, @StoutFiles great stuff, I didn't know you could do that!

I realised that I can use this function and avoid defining the &_POST variables. It will automatically grab everything that is $_POSTed to this script and write into an array. Brilliant! Thank you very much!
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members