开发者

PHP Looping....need some advice

I have the fo开发者_如何学运维llowing code:

$q1 = $_POST["q1"];
$q2 = $_POST["q2"];
$q3 = $_POST["q3"];
$q4 = $_POST["q4"];
$q5 = $_POST["q5"];
$q6 = $_POST["q6"];
$q7 = $_POST["q7"];
$q8 = $_POST["q8"];

At the moment, this is hard coded and I need to manually change it each time, I'd like to use variables instead so that it's not a manual process.

Is it a case of using a loop, while or foreach?

If I had the the information $q and q in an array would that help?

Thanks,

Homer.


Consider adjusting your forms to use Array notation, e.g.

<ul>
    <li><input name="q[]" /></li>
    <li><input name="q[]" /></li>
    <li><input name="q[]" /></li>
    <li><input name="q[]" /></li>
    ...
</ul>

This would make $_POST['q'] contain an array with all input values given for 'q', which you can then easily iterate over with foreach like this:

foreach($_POST['q'] as $q) {
    // do something with $q
}

See http://www.johnrockefeller.net/html-input-forms-sending-in-an-array-in-php/


Yes this is the time for a loop. You can use foreach or while, it does not really matter.

$i = 1; 
$q = array(); 
while($i < 9) {
    $q[$i] = $_POST["q" . $i];
    $i += 1;
}


1.

$keys = array('q1', 'q2', 'q3', 'q5', 'q9');
$q = array();
foreach ( $keys as $key ) {

  $q[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
}

2.

$keys = array('q1', 'q2', 'q3', 'q5', 'q9');
foreach ( $keys as $key ) {
  $$key = isset($_POST[$key]) ? $_POST[$key] : null;
}
// in output you will have variables called $q1, $q2, $q3, ...

3.

$amount = 8;
$q = array();
for ( $i = 1; $i <= $amount; ++$i ) {
  $q[$i] = isset($_POST['q' . $i]) ? $_POST['q' . $i] : null;
}


Untested, and it's been a while since I last used PHP:

$q = array();
for ($i = 1; $i <= 8; ++$i)
    $q[$i] = $_POST["q" . $i];


Try following code, in case if it's ok with you to save POST data to another array:

// Random POST array
$_POST["q1"] = 1;
$_POST["q2"] = 2;
$_POST["q3"] = 3;
$_POST["q4"] = 4;
$_POST["q5"] = 5;
$_POST["q6"] = 6;
$_POST["q7"] = 7;
$_POST["q8"] = 8;

$array = Array( );

foreach ( $_POST as $value ) {
    $array[ ] = $value;
}

In case you want to save POST data into more specific variables, you'll have to use bit more complex piece of code. Can edit my post if you want to see more options.

Edit:

If you wanted to work just with keys that start with q and end with number, you could use following code:

$array = Array( );

foreach ( $_POST as $key => $value ) {
    if ( preg_match( "/^[q]{1}\d$/", $key ) ) {
        $array[ ] = $value;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜