Reputation: 413
I have a function that can either be called by echo or load, in turn also 0 or 1 for echo or load. But, since adding the number variable to the function options, it no longer always works.
Can you please help me?
Here is my function:
// GET MAIN INFORMATION
function get_info ($KEY, $OUTPUT = 0) {
$KEY = "_" . strtoupper($KEY);
if ($OUTPUT == "echo" || $OUTPUT == 0):
echo "echo " . constant($KEY);
elseif ($OUTPUT == "load" || $OUTPUT == 1):
return "load " . constant($KEY);
endif;
}
now when I try to call the function like this:
echo 1;
get_info('scripts_url', 'echo');
echo "<br>" . 2;
get_info('scripts_url', 0);
echo "<br>" . 3;
echo get_info('scripts_url', 'load');
echo "<br>" . 4;
echo get_info('scripts_url', 1);
This is my output:
1echo scripts/ (This is correct!)
2echo scripts/ (This is correct!)
3echo scripts/ (This is not correct!)
4load scripts/ (This is correct!)
So there is an issue when I try to use the numbers. Can you see the error and help me correct it?
Thanks
Upvotes: 1
Views: 32
Reputation: 270637
Owing to PHP's rules for boolean comparisons, the non-numeric string "load"
compares truthfully to the integer 0
. So your first condition will match any string that can't be converted directly to a non-zero integer. Instead of loosely comparing via ==
, use a strict comparison via ===
.
function get_info($key, $output = 0)
{
$key = "_" . strtoupper($key);
// Strict comparisons should be used to avoid strings matching int 0
if ($output === "echo" || $output === 0) {
echo "echo " . constant($key);
} elseif ($output === "load" || $output === 1) {
return "load " . constant($key);
}
}
An aside, not relevant to your question, but the alternate flow control style in PHP (if/elseif/endif
and its loop cousins) are mainly intended for templating inside HTML. It's sort of unconventional to use them in straight PHP, where using the standard curly brace syntax is preferred. (if {}
). If you're going to integrate with others' code, consider using the standard syntax instead.
Upvotes: 2