I'm using PHP to access an external API.
When a call a particular API method, it returns a number one higher than I want to display.
However, the API is returning the integer as a string and not an integer.
Question: How can I decrement the returned string by 1 since it's not an integer
Essentially, I want to do the follow pseudo-code (that doesn't work):
echo external_api() -1; // problem is, this returns "X -1" where "X" is an integer but returned as a strong
Cast it with (int)
or use intval()
to convert it to an integer first:
echo ((int) external_api()) - 1;
or
echo intval(external_api()) - 1;
Casting is generally the fastest.
You can cast the return value as integer :
echo ((int) external_api()) - 1;
** EDIT **
This is the code that I ran
function external_api() {
return "100";
}
echo ((int) external_api()) - 1;
and the output is 99
. If this doesn't work for you, then the function is not returning a correct value. Otherwise, please elaborate because it doesn't make any sense.
Moreover, as deceze pointed out, even without casting, PHP is smart enough to do it already on math operators :
echo external_api() - 1;
will also output 99
so obviously there is something going on in that mysterious function because the problem is not where you say it is.
BTW : the result of "2" -1
; can never be "2 -1"
because -
is not even a string operator. The only string operator in PHP is .
for concatenation: "2" + 1 = 3;
where "2" . 1 = "21"
try echo intval(external_api())-1
or if some higher no or other data type floatval too
If the function is returning a string, then your code should actually work. You could try casting the value to an integer though:
echo (int)external_api() - 1;
EDIT
It sounds like you might need to sanitize your data using preg_replace before decrementing it. Try this:
echo preg_replace('/[^0-9]/', '', external_api()) - 1;
The external_api()
function echoes the integer (9
) and returns NULL
. Thus, when you attempt to subtract from it, you get something like the following:
function external_api() {echo "9";}
echo external_api() - 1;
...which would produce 9-1
.
Mystery solved.
Now, to fix it. Supposing you can't change the external api...
ob_start();
external_api();
$output = ob_get_clean();
echo ((int)$output) - 1;
Next time, though, post everything, so we're not scratching our heads for an extended period of time.