nikolas
nikolas

Reputation: 722

Passing array with values php

is it possible to pass through $_POST or $_GET an array, with values in it, without using serialize() and unserialize() ? here is an example code, trying to find a number..i entered value 4 instead of rand, just to do the testing.. i thought of the potential of using a foreach to make multiple input hidden, in case i could pass all variables every single time, but it seems not to be working.. any ideas..??? or it is just not possible without serializing?

<?php
$x = $_POST['x'];
$Num = $_POST['Num'];
$first_name[] = $_POST['first_name'];
if (!$x)
{
Echo "Please Choose a Number 1-100 <p>";
$x = 4; //rand (1,4) ;
} 
else {
if ($Num >$x)
{Echo "Your number, $Num, is too high. Please try again<p>";}
elseif ($Num == $x)
{Echo "Congratulations you have won!<p>";
Echo "To play again, please Choose a Number 1-100 <p>";
$x = 4;// rand (1,4) ;
}
else 
{Echo "Your number, $Num, is too low. Please try again<p>";}
}
?> 
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> <p> 
Your Guess:<input name="Num" /> 
<input type = "submit" name = "Guess"/> <p> 
<input type = "hidden" name = "x" value=<?php echo $x ?>> 
<?php
foreach($first_name as $val){
echo "<input type=\"hidden\" name=\"first_name[]\" value=$val />";
}
?>
</form> 
</body> 
</html> 

Upvotes: 1

Views: 2689

Answers (2)

nikolas
nikolas

Reputation: 722

here is the solution that i figured out...

    $x = $_POST['x'];
    $Num = $_POST['Num'];
    $first_name = $_POST['first_name']; //creating array from the begining
    $first_name[] = $Num; // add current num to next available slot in array
    $counter = $_POST['counter'] +1;
    if (!$x) // below this is the same..
    ....
    ....
    <input type = "hidden" name = "x" value=<?php echo $x; ?>> 
    <input type = "hidden" name = "counter" value=<?php echo $counter; ?>> //add a counter to count loops
    <?php 
    if ($counter>=2){ //counter in first load of page will be 1, so we need to read enter value from the next load of page
    for ($i=0; $i<=($counter-2); $i++){  // counter-2 gives us the actual number of elements
    echo "<input type=\"hidden\" name=\"first_name[]\" value=$first_name[$i] />";
    }
    }
    ?>
     </form> 

Upvotes: 0

didierc
didierc

Reputation: 14730

<?php
    foreach($first_name as $k => $val)
        echo "<input type='hidden' name='first_name[$k]' value='$val' />";

should work.

Upvotes: 1

Related Questions