Reputation: 323
I'm just starting with PHP and have written a small PHP console program to take 5 test scores and return the appropriate grades plus average. (I am aware my determineGrade function is incomplete - I left it that way to work on the rest of the program structure first ).
My issue is that this line:
echo "Test #{$index}: {determineGrade($grades[$index])}.\n";
Inside the second for loop does not produce any output.enter code here
for($index = 1; $index <= 5; $index++)
{
echo "Enter Test Score #{$index}:";
$grades[$index] = trim(intval(fgets(STDIN)));
}
echo "\n\n ==== Results: =====\n";
for($index =1; $index <= 5; $index++)
{
echo "Test #{$index}: {determineGrade($grades[$index])}.\n";
}
$average = calcAverage($grades);
function calcAverage($gradesArray)
{
// initialize a variable to hold the sum, calculated in loop
$sumTotal = 0;
// start this loop at $index=1 for consistency. Sum the grades.
for($index=1; $index <= count($gradesArray); $index++)
{
$sumTotal = $sumTotal + $gradesArray[$index];
}
return $sumTotal / 5;
}
function determineGrade($gradeToDetermine)
{
if($gradeToDetermine >= 90)
{
return "A";
} else if($gradeToDetermine >= 80)
{
return "B";
}
}
?>
I've tried this with inputs like 87 that ought to produce a result but no go.
Thank you for your help, Marc
Upvotes: 0
Views: 47
Reputation: 41810
The complex string syntax (curly brackets in a double quoted string) won't execute your determineGrade
function. You'll have to concatenate that into your output instead.
echo "Test #{$index}: " . determineGrade($grades[$index]) . "\n";
or pass the different pieces as multiple parameters to echo
.
echo "Test #{$index}: " , determineGrade($grades[$index]) , "\n";
Technically, functions can be executed in the curly braces, but only to return the names of variables. See this note from the documentation:
Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
So you could use
echo "Test #{$index}: {${determineGrade($grades[$index])}} \n";
If you happened to have variables named $A
, $B
, etc.
This probably won't be helpful to you in this situation, but I just thought I should mention it for future reference since the first part of the answer could be interpreted as not strictly correct.
Upvotes: 4