Welcome to WebmasterWorld Guest from 54.159.165.175

Forum Moderators: coopster & jatar k

Writing an unpredictable number of variables into an Array

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

5+ Year Member



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)

WebmasterWorld Senior Member 5+ Year Member



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

WebmasterWorld Senior Member 10+ Year Member



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)

5+ Year Member



@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!
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month