pjc2003 Posted January 9, 2007 Share Posted January 9, 2007 hi there,i want to create a loop that changes the value of a variable based on the value of another variable i.eif{$variable_one = "A"then$variable_two ="1"} etcbut i want it for 26 options so it can deal with all 26 possible values of variable 1? Just a bit stuck on how to write the code?Many thanks.Peter. Link to comment https://forums.phpfreaks.com/topic/33458-creating-a-loop-to-change-variable-value/ Share on other sites More sharing options...
obsidian Posted January 9, 2007 Share Posted January 9, 2007 Typically, you'd want to use a switch statement for that. Something like this should get you on your way:[code]<?php$var1 = 'A';switch($var1) { case 'A': $var2 = 1; break; case 'B': $var2 = 2; break; case 'C': $var2 = 3; break; // etc. until all your 26 cases are set.}?>[/code]Another option would be to develop a pattern that will remain true throughout your process, and write a single loop for all of them. For instance, if you are simply incrementing the value of your second variable for each letter of the alphabet (from 1 - 26), you could set up a handling array and simply assign the values like this:[code]<?php// Start by priming your variables.$alpha = array();$x = 'A';for ($i = 1; $i <= 26; $i++) { $alpha[$x] = $i; ++$x;}// Now, all you have to do is assign the values$var1 = 'A'; // value of 'A'$var2 = $alpha[$var1]; // value of 1?>[/code]Hope this helps Link to comment https://forums.phpfreaks.com/topic/33458-creating-a-loop-to-change-variable-value/#findComment-156609 Share on other sites More sharing options...
Accipiter Posted January 9, 2007 Share Posted January 9, 2007 You can also create the array directly containing all the 26 different values (Incase there is no obvious pattern to the values. Otherwise the above example is more suitable):[code]$switch_array = array('A'=>1, 'B'=>2, 'C'=>12, 'D'=>9); // Etc. etc.$variable_two = $switch_array($variable_one);[/code]Good luck :) Link to comment https://forums.phpfreaks.com/topic/33458-creating-a-loop-to-change-variable-value/#findComment-156616 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.