How do I cycle through REQUEST and use dynamic variable naming? PHP ! :)
I have a form that submits details of multiple people i.e in the $_REQUEST I get :
title1 = Mr,
first_name1 = 'Whatever',
surname1 = 'Whatever',
title2 = Mr,
first_name2 = 'Whatever',
surname2 = 'Whatever'
There's obviously more but this explains the situation. There could be ten people being submitted and therefore it would go up to title10, first_name10, surname10...
I have been trying to use:
for ($x = 1; $x < 4; $x++) {
$a = new applicant();
$a->title = $_REQUEST['title'+$x];
$a->first_name = $_REQUEST['first_name'+$x];
$a->surname = $_REQUEST['surname'+$x];
$a->Save();
}
However it appears that you cannot do this +$x bit. I know there is a way around it since I remember doing this ages ago yet I don't have my code 开发者_如何转开发at work :/
Any ideas guys?
PHP uses .
for concatenating strings, and +
for adding numbers; this is different from some other languages which use +
for both. Possibly confusing, but unlikely to change.
'title' + $x
will try to add the parts as if they were numbers, casting if necessary.
'title' . $x
should do what you seem to be looking for.
Read also: The Fine Manual
String concatenation in PHP uses the operator .
not +
. For example: $_REQUEST['title' . $x];
You can use the same attribute name in your HTML form for mulitple inputs like so:
<input name="title[]" />
...
<input name="title[]" />
Which when submitted to the PHP script will be available in the GET/POST as an array already.
you may try this:
$a = "first part";
$b = "second part";
$c = ${$a.$b};
or something like
$c = $_REQUEST[${$a.$b}];
Anyway, you got the idea.
精彩评论