1

I have a while loop that loops through 3 results and echo's these out in a list. It will always be 3 results.

Here is my current PHP:

while($row = sqlsrv_fetch_array($res))
{

    echo "<li>".$row['SessionValue']."</li>";
    // prefer to store each value in its own variable

}

However I'd like to store the $row['SessionValue'] value in each loop in a new variable.

So....

first loop: $i0 = $row['SessionValue'];

second loop: $i1 = $row['SessionValue'];

third loop: $i2 = $row['SessionValue'];

How would I achieve this with PHP?

Many thanks for any pointers.

2
  • 3
    put it in an array.. btw, tell us what you're really trying to do (not how you're trying to do it) Commented Mar 29, 2012 at 8:43
  • Thanks Karoly. Sorry, that's a good point. I'll try to approach it in that way next time. Can you explain how I would do this using an array? Commented Mar 29, 2012 at 8:51

3 Answers 3

1
$lst_count = array();
while($row = sqlsrv_fetch_array($res))
  $lst_count[] = $row["SessionValue"];
Sign up to request clarification or add additional context in comments.

2 Comments

You're welcome... (Karoly already suggested this before I finished my answer).
Strictly speaking, Niko's answer - which creates 3 separate variables - is what you actually wanted.
1

You just need another variable that gets incremented:

$count = 0;
while($row = sqlsrv_fetch_array($res))
{
    ${i.$count++} = $row['SessionValue'];
}

5 Comments

Hi Niko. I'm afraid this gives me no variables in the loop.
Put var_dump($i0); after the loop, it will output the first value!
Thank you, Niko. Will try just now.
Though I would recommend using the solution with an array, that will turn out to be easier to handle.
Your answer certainly answered my question, but you guys are right, there was a better way to do it. Thanks for your time and effort here sir.
1

You can do this have SUM of all value:

$total = array();
while($row = sqlsrv_fetch_array($res))
{
   $total[] = $row["SessionValue"]
}  $sumAll = array_sum($total);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.