Reputation: 71
Is it possible to do something like this? I'm new to this so don't know!
//row 1 in mysql array
$var = "hello";
$id = 1;
//row 2 in mysql array
$var = "bye";
$id = 2;
//Closing while loop
//Is the following possible?
echo $var1; //outputs "hello"
echo $var2; //outputs "bye"
Upvotes: 0
Views: 119
Reputation: 16313
// Define them both as arrays
$var = array();
$id = array();
// In your loop
$var[] = "hello";
$id[] = 1;
// Next iteration
$var[] = "bye";
$id[] = 2;
// Printing them out
echo $var[0]; // prints out "hello"
echo $var[1]; // prints out "bye"
Using arrays^^
Alternatively:
$rows = array();
// In your loop
$rows[] = array("id" => 1, "var" => "hello");
// Next iteration
$rows[] = array("id" => 2, "var" => "bye");
// Print them out
echo $rows[0]["var"]; // Prints hello
echo $rows[1]["var"]; // Prints bye
Upvotes: 0
Reputation: 5705
You mention MySQL. So a more complete example of what you want to achieve would be:
$var = array();
$id = array();
while ($row = mysql_fetch_assoc($result)) {
$var[] = $row['text']; // don't know how the column is named
$id[] = $row['id'];
}
echo $row[0]; // hello
echo $row[1]; // bye
With a looping variable i
:
$var = array();
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
$var[$i] = $row['text']; // don't know how the column is named
$i++;
}
echo $row[1]; // hello
echo $row[2]; // bye
Upvotes: 0
Reputation: 81
I would do so
$id = 1;
$var[$id] = "hello";
$id = 2;
$var[$id] = "bye";
echo $var['1'];
echo $var['2'];
// or
echo $var[$id];
Upvotes: 0
Reputation: 1002
Not like you want, you can use an array though:
$var[1] = "hello";
$var[2] = "bye";
echo $var[1];
echo $var[2];
Upvotes: 3