mrherman Posted July 9, 2010 Share Posted July 9, 2010 If I have a whole bunch of numeric variables that I need to initialize to 0, is there a "wholesale" way of coding this, other than $var1 = 0, $var2=0, etc... Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/ Share on other sites More sharing options...
kenrbnsn Posted July 9, 2010 Share Posted July 9, 2010 What do the variable names look like? Ken Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/#findComment-1083750 Share on other sites More sharing options...
Wolphie Posted July 9, 2010 Share Posted July 9, 2010 I guess the easiest way would be to use: <?php $num_of_vars = 10; $prefix = 'var'; for ($i = 0; $i <= $num_of_vars; $i++) { ${$prefix . $i} = 0; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/#findComment-1083756 Share on other sites More sharing options...
mrherman Posted July 9, 2010 Author Share Posted July 9, 2010 Oh, sorry, I was using $var as an example...The actual variables have names of different length, such as... $totalcorrect $totalitems $pctcorrect $appcount I was wondering if you can do something like (although I know this will not work): Store 0 to $totalcorrect, $totalcnt, $....... ; Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/#findComment-1083759 Share on other sites More sharing options...
Wolphie Posted July 9, 2010 Share Posted July 9, 2010 The only way to do that would be to make an array which stores the variable names. <?php $var_name = array('totalcorrect', 'totalitems', 'pctcorrect', 'appcount'); foreach ($var_name as $name) { ${$name} = 0; } ?> So this still involves a bit of manual work. Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/#findComment-1083762 Share on other sites More sharing options...
mrherman Posted July 9, 2010 Author Share Posted July 9, 2010 Wolphie -- that is helpful. It does help a little. Thanks!! Quote Link to comment https://forums.phpfreaks.com/topic/207275-initializing-lots-of-numeric-variables-to-0-best-way-to-code/#findComment-1083773 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.