chrisran Posted January 25, 2011 Share Posted January 25, 2011 Hi ! I'd like to count all occurences in "$thiscodestring" into a "dynamic?" array and print it out after the end of the loop, how do I assign the variablenames dynamically ? $query = "SELECT codes, status FROM table"; while ($row = mysql_fetch_assoc($result)) { $thiscodestring = $row[codes]; // looks like "a1 c2 d3 10 15 1 a1 a1"; $singlecodes = explode(" ", $thiscodestring); foreach($singlecodes as $thiscode) { $$thiscode[count] = $$thiscode[count] + 1; } } After all Mysql-Stuff is done I'd like to print out the counted codes, for example the code "a1" was found 100 times in all querys then $$a1[count] should be 100, c2 was found 15 times, then $$c2[count] should be 15 and so on. Question: How do I tell php to assign a "dynamic" variable with the name of the found string which was exploded (in this example a1, c2, d3... ) before ?! $$ does not seem to work. And how can I then print_r() the value if I dont know the name ? Thanks ! Link to comment https://forums.phpfreaks.com/topic/225603-dynamic-variable-array/ Share on other sites More sharing options...
Roman Fedorov Posted January 25, 2011 Share Posted January 25, 2011 Hi chrisran, you should just use an array, using $thiscode as the key, and incrementin the value: $query = "SELECT codes, status FROM table"; $codes = Array(); while ($row = mysql_fetch_assoc($result)) { $thiscodestring = $row[codes]; // looks like "a1 c2 d3 10 15 1 a1 a1"; $singlecodes = explode(" ", $thiscodestring); foreach($singlecodes as $thiscode) { $codes[$thiscode]++; } print_r($codes); } Link to comment https://forums.phpfreaks.com/topic/225603-dynamic-variable-array/#findComment-1164914 Share on other sites More sharing options...
parino_esquilado Posted January 25, 2011 Share Posted January 25, 2011 To create a dynamic variable you need to wrap the second dollar with {} curly braces: <?php $variableName = "a1"; ${$variableName} = 100; ?> which would create a an $a1 variable with the value of 100 ($a1 = 100). Link to comment https://forums.phpfreaks.com/topic/225603-dynamic-variable-array/#findComment-1164962 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.