deb
deb

Reputation: 51

How to get for loop data outside for loop

I want the loop data out side forloop, but i'm getting only one value

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">

               <select name="test[]"  multiple="multiple">
                    <option value="test">test</option>
                    <option value="mytesting">mytesting</option>
                    <option value="testingvalue">testingvalue</option>
                    </select>
                <input type="submit" value="Send" />
                   </form>


<?php
    $test=$_POST['test'];
    for($i=0;$i<count($test);$i++)
    {
    $tyy = $test[$i];
    }


?>

I want to get $tyy out side for loop

I want the loop data out side forloop by i am getting only one value

Upvotes: -1

Views: 6102

Answers (6)

user2745280
user2745280

Reputation: 21

But why are you use loop for post data. Your $_POST['test'] is self array so you can use it without for loop. $array = $_POST['test']; try this.

Upvotes: -1

Alun
Alun

Reputation: 23

You have created one single variable, which is being overwritten each time you loop, so there is only one value to get.

If you want to access all the values, you need to save into an array instead of a single variable, or append all the values into one value

either

//create an array of values in $tyy
$tyy = $_POST['test'];
//you can now access $tyy by looping through it.

or

$test = $_POST['test'];
$for($i = 0; $i<count($test); $i++)
{
  //list all the values with commas separating them.
  $tyy .= $test[$i].", ";
}

//view the contents by echoing it.
echo $tyy;

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This is, because you are reassigning it every iteration. So change the line to this:

$tyy[] = $test[$i];
  //^^ See here, Now you are assign the value to a new array element every iteration

So that you have an array which you can use later

Side Note:

1. You know that you already have an array with this data in $test ? But if you want all data as one string you can use this (without a for loop):

$tyy = implode(", ", $test);

2. $_SERVER["PHP_SELF"] is just a reflection of your URL, so this is open for XSS. You can use this to make it save:

<?= htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>

Upvotes: 0

Rajnikant Sharma
Rajnikant Sharma

Reputation: 606

Use $tyy as an array and fill that array in for loop by using array_push method.

 $tyy = array();

 $test=$_POST['test'];
for($i=0;$i<count($test);$i++)
{
   array_push($tyy, $test[$i]);
}

Upvotes: 0

Sarath Kumar
Sarath Kumar

Reputation: 2353

try this..

    $groupStr = "";
    for($i=0; $i< count($test); $i++)
        {
        $groupStr .= $test[$i];
        }

echo $groupStr;

Upvotes: 1

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Use this

$tyy[] = $test[$i];

or you can concat the values by using this

$tyy = "";
for($i=0;$i<count($test);$i++)
    {
    $tyy .= $test[$i];
    }

print_r($tyy)

Upvotes: 1

Related Questions