Forum Moderators: coopster

Message Too Old, No Replies

assigning array elements to variables

using foreach

         

stef25

9:39 am on Apr 16, 2007 (gmt 0)

10+ Year Member



code below prints out the 5 values grabbed by the sql query. what im trying to do is assign these values to variables (dynamically via a loop?) so i can easily insert them in different locations on my page.

Is there a way i can do something like $var0 = array element[0], $var1 = array element[1], etc?


$query = "SELECT price FROM pans";
$result = mysql_query($query,$connection)
or die ("problem");
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($line as $col_value) {
echo "<p>$col_value</p>";
}
}

cameraman

10:16 am on Apr 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's several different ways you can do it. Personally I think it's easier to deal with them in an array. Since you're only grabbing one field with your query, you don't really need your foreach loop; right after the while statement,
$line['price']
is the value obtained from the query.
To put the values into an array called prices:
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$prices[] = $line['price'];
}

Afterward you'd have $prices[0], $prices[1], $prices[2]...

If you have an aversion to arrays, you can put the values into scalar variables (like $var0) by using a php feature called variable variables [us.php.net].
$num = 0;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$variablename = 'var' . $num;
$$variablename = $line['prices'];
$num++;
}

Afterward, you'd have five variables with names as you described: $var0, $var1, $var2...

adb64

10:52 am on Apr 16, 2007 (gmt 0)

10+ Year Member



Adapt the following example to your needs:

$i = 1;
$varname = "var$i";
$$varname = "Hello World";
echo $var1;

This code will printout the value for $var1 being "Hello World".

joelgreen

3:30 pm on Apr 16, 2007 (gmt 0)

10+ Year Member



Lets say you have this array

$cols = array('mama' => 'mia', 'father' => 'john');

This code: extract($cols);

will create variables

$mama = 'mia';
$father = 'john';

If you do $line = mysql_fetch_assoc($result, MYSQL_ASSOC)

then you can do extract($line) to get all the variables