[PHP] Fill array with $_POST[]

I’d like to use as less variables as possible so i want to create a list of $_POST into an array. However it doesn’t work:


$array = array($_POST['username'],$_POST['password'],$_POST['etc']);
//etc

It works if i use this, but i think this can be written shorter


$username = $_POST['username'];
// etc
$array = array($username, $password);
//etc

Is there a way to include all $_POST’s into an array without using variables first?

It’s because you are using array as the variable name. It’s a reserved word.

hmm but it does work with variables… i’ll change it anyway, see if it helps.

Nope doesn’t work :frowning:

I can’t find any information about it but is it possible and if so how do i use it?


$lijst = array($_POST['username'], $_POST['password']);

I guess you’re trying to access the values wrong:


$list = array($_POST['username'], $_POST['password']);

echo $list['username']; //this won't work

echo $list[0]; //this will work

To access the value by name, you should create an associative array:


$list = array('username'=>$_POST['username'], 'password'=>$_POST['password']);

echo $list['username']; //now this will work

BTW, you can use $array as a variable name, it is not reserved at all.

I don’t know what went wrong the first time, since i already did exactly what you said, but i’ve got it working now. Thanks a lot!

I’d like to use as less variables as possible so i want to create a list of $_POST into an array.

Then why not just use $_POST instead of creating another array?

Hmm another problem with the arrays (sorry for my newbie-ism).

I have like 100 questions using radiobuttons. Each question has it’s own name (1,2,3,4,etc) and each has a set of 5 answers (a,b,c,d,e).

Instead of listing all 100 answers in $_POST i’d like to build an array using this:


<?php
$uitslag = 0;
for ($a=0; $a<100; $a++) {
	$lijst = array ($_POST[$a]);
	switch ( $lijst[$a] ) {
		case "a": $uitslag = $uitslag + 4; break;
		case "b": $uitslag = $uitslag + 3; break;
		case "c": $uitslag = $uitslag + 2; break;
		case "d": $uitslag = $uitslag + 1; break;
		default: $uitslag = $uitslag + 0; break; }}
echo "$uitslag";
?>

That doesn’t seem to work. Is this possible or should i just name all $_POST?

Markl999 > That’s a though question… iam pretty new to PHP so iam trying to create code as clean as possible. I’ll look into a solution of your suggestion. :slight_smile:

You could maybe do something like this:

<?php
foreach ($_POST as $key => $value) {
  $lijst[$key] = $value;
}
?>

to iterate through the POST collection without specifying all the keys explicitly.

Thanks, i’ll try this!