开发者

defining alphabets as numbers not working inside loop

开发者 https://www.devze.com 2023-04-07 20:32 出处:网络
Please check my code below,it returns 0 while I am expecting a result 14.But when I add A+D manually 开发者_开发百科it returns 5.Am i doing something wrong inside the loop ?

Please check my code below,it returns 0 while I am expecting a result 14.But when I add A+D manually 开发者_开发百科it returns 5.Am i doing something wrong inside the loop ?

<?php
    define('A',1);
    define('B',2);
    define('C',3);
    define('D',4);
    define('E',5);

    //echo A+D; returns 5

    $name = 'EACE';

    $len = strlen($name);

    for($i = 0; $i<=$len; $i++)
    {
        $val += $name[$i]; 
    }
    echo $val;   //returns 0

?>


You need to use constant(..) to get the value of a constant by name. Try this:

for ($i = 0; $i < strlen($name); $i++) {
    $val += constant($name[$i]);
}


define('A',1);
define('B',2);
define('C',3);
define('D',4);
define('E',5);

//echo A+D; returns 5

$name = 'EACE';

$len = strlen($name);

$val = null;

for($i = 0; $i<=$len-1; $i++)
{
    $val += constant($name[$i]); 
}
echo $val;
0

精彩评论

暂无评论...
验证码 换一张
取 消