defining alphabets as numbers not working inside 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;
精彩评论