Jump to content

creating a loop to change variable value


pjc2003

Recommended Posts

hi there,

i want to create a loop that changes the value of a variable based on the value of another variable

i.e

if{

$variable_one = "A"

then

$variable_two ="1"


} etc


but 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

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
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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.