AssamGuy
AssamGuy

Reputation: 1593

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

?>

Upvotes: 0

Views: 101

Answers (2)

Rusty Fausak
Rusty Fausak

Reputation: 7525

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]);
}

Upvotes: 3

Nicklasos
Nicklasos

Reputation: 565

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;

Upvotes: 1

Related Questions