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.

share|improve this question

67% accept rate
feedback

7 Answers

up vote 1 down vote accepted
$varname = $row['State'] . '_count';
$$varname = 0; // or 1
share|improve this answer
feedback

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']].

share|improve this answer
1  
I've never thought of a good place to use variable variables where an associative array wouldn't be better. Though you do need to say: $count[$row['State']] (missing $ on row) – Johrn Jan 21 '10 at 15:54
@Johnr: yep, I agree. Thanks for the note. I have fixed it now. – Aishwar Jan 21 '10 at 15:58
feedback

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

$var_name = "{$row['State']}_count";
$$var_name = 1;
share|improve this answer
feedback

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;
share|improve this answer
feedback

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
share|improve this answer
thank you for all your responses. – JPro Jan 21 '10 at 16:01
feedback

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

share|improve this answer
feedback

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.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.