Wyatt Jackson
Wyatt Jackson

Reputation: 303

How do I easily find the sum of variables corresponding to a dynamic string variable?

I'm completely stumped on how to accomplish my task programmatically.

I have a dynamically changing alpha string variable named $string. I have corresponding values set to each letter in the alphabet. I need to be able to automatically calculate the value of $total_string_length based on the letters within the $string variable.

$string = "jack"

$A_length = 1000;
$B_length = 500;
$C_length = 200;
$D_length = 1000;
$E_length = 1400;
$F_length = 100;
$G_length = 5000;
$H_length = 2000;
$I_length = 600;
$J_length = 8000;
$K_length = 8000;
etc...

$total_string_length = $J_length  + $A_length + $C_length + $K_length

How do I easily substitute the corresponding alpha letter variable values to find the $total_string_length ?

Any help is much appreciated.

Upvotes: 0

Views: 119

Answers (2)

Parshav Jain
Parshav Jain

Reputation: 1

Not much into PHP, But in Java we can do something as below:

  1. Create an integer array of size 26 (number of letters in the alphabet) and load the length value of each variable's first character based on its index i.e.,

    intArr[(int)"A_length".charAt(0) - 65] = 1000;
    
  2. Iterate through the characters of the string and get the value as stated below:

    for ( char ch : string.tocharArray() ) {
            sum += intArr[(int)ch - 65 ];
    }
    

Upvotes: 0

Hieu Le
Hieu Le

Reputation: 8415

PHP can use dynamic variable names.

$string = "jack";

$A_length = 1000;
$B_length = 500;
$C_length = 200;
$D_length = 1000;
$E_length = 1400;
$F_length = 100;
$G_length = 5000;
$H_length = 2000;
$I_length = 600;
$J_length = 8000;
$K_length = 8000;

$output = 0;
for($i = 0; $i < strlen($string); $i++) {
    $varName = strtoupper($string[$i]) . "_length";
    $output += $$varName; // notice the double `$` charaters
}

echo $output;

In the above code snippet, the value of the $varName variable is the name of the variable we want to get the number from. If $varName is A_length then $$varName is equivalent to $A_length.

However, it's better to store your number in an array instead of a list of separated variables.

Upvotes: 3

Related Questions