VanMeter Posted August 22, 2008 Share Posted August 22, 2008 Is there a way to call a specific variable by adding the i from a for loop? For example: I have variables Branch0 Branch1 Branch2 being submitted from a form to be processed. I am using a for loop to write the values of these variables. I tried this but it doesn't work: for ( $i = 0; $i < 15; $i++ ){ echo $Branch$i; } I also tried this: for ( $i = 0; $i < 15; $i++ ){ echo $Branch+$i; } So is there any way to call a variable using the i to specify which variable...? I know I could use an array but it doesn't work for this application ??? Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/ Share on other sites More sharing options...
Zane Posted August 22, 2008 Share Posted August 22, 2008 $Branch{$i} or you can try $varName = "Branch" . $i; echo $$varName; This is called Variable Variables Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623249 Share on other sites More sharing options...
thebadbad Posted August 22, 2008 Share Posted August 22, 2008 <?php for ( $i = 0; $i < 15; $i++ ){ $var_name = "Branch$i"; echo $$var_name; } ?> Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623250 Share on other sites More sharing options...
Barand Posted August 22, 2008 Share Posted August 22, 2008 It much simpler to use an array than mess with variable variable names. Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623265 Share on other sites More sharing options...
thebadbad Posted August 22, 2008 Share Posted August 22, 2008 It much simpler to use an array than mess with variable variable names. Sure thing. I like how you edited your post to include my method, zanus. lol Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623287 Share on other sites More sharing options...
Zane Posted August 23, 2008 Share Posted August 23, 2008 heh...just a coincidence really. but if you want to think I copied you then...fine with me Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623484 Share on other sites More sharing options...
thebadbad Posted August 23, 2008 Share Posted August 23, 2008 heh...just a coincidence really. but if you want to think I copied you then...fine with me Oh, didn't mean to bother you then. Link to comment https://forums.phpfreaks.com/topic/120908-add-i-from-for-loop-to-the-end-of-a-variable/#findComment-623672 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.