JPro
JPro

Reputation: 6556

Creating Variable Variables from MySQL Values

Is it possible to create a dynamic variable in PHP based on the value that comes from mysql database?

I mean,

say I have a field in mysql State

When I read the value in php using row['State'] from the database and if I get a value like Alabama, I want to have a variable created like $Alabama_count and I will initialize to 0 or 1.

Thanks.

Upvotes: 2

Views: 921

Answers (7)

Aishwar
Aishwar

Reputation: 9724

There does exist an easier solution. Instead of creating something called $Alabama_count, you could create this very easily: $count['Alabama'], i.e. $count[$row['State']].

Upvotes: 3

Javi
Javi

Reputation: 19799

You can use for this variables of variables using $ symbol twice: for example:

$variable = 'Some_text';
$$name = 123;
echo $Some_text;
//this will output 123

Upvotes: 0

Amish Programmer
Amish Programmer

Reputation: 2121

You could create a variable named ${$row['State'].'_count'} and set its value. I'm not sure how advisable this would be, however. You don't know what variables you will be left with.

Upvotes: 0

AntonioCS
AntonioCS

Reputation: 8506

Not really sure if this is what you want but take a look at Variable variables on the php manual

Upvotes: 0

Alix Axel
Alix Axel

Reputation: 154691

You can do ${$row['State']} if $row['State'] is Alabama it's the same as doing $Alabama.

Similarly you can do the same to _count:

${$row['State'] . '_count'} = 0; // $Alabama_count = 0;
${$row['State'] . '_count'}++; // $Alabama_count++; // $Alabama_count = 1;

Upvotes: 1

OneNerd
OneNerd

Reputation: 6552

Sounds like you want to use variable variables, something like this?

$var_name = "{$row['State']}_count";
$$var_name = 1;

Upvotes: 0

Aistina
Aistina

Reputation: 12679

$varname = $row['State'] . '_count';
$$varname = 0; // or 1

Upvotes: 1

Related Questions