duancan8382 2018-08-09 10:15
浏览 15
已采纳

如何轻松找到与动态字符串变量对应的变量总和?

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.

  • 写回答

2条回答 默认 最新

  • dqenv99518 2018-08-09 10:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?