php function integer parameter problem
function is_zipcode_valid($zipcode){ ... }
if I call that function with is_zipcode_valid(08004);
my paramete开发者_开发问答r 08004 gets in as 8004, basically it removed all precending 0's.
How can I get around that problem?
thanks
Pass it as a string and modify your function to expect a string instead:
is_zipcode_valid('08004');
It's not possible to preserve leading zeros when using integers. If an integer value has a leading zero, it is interpreted in base 8. Here is an example:
echo 010; // Output is 8.
PHP treats integers as base8 numbers if a leading zero is present. Pass your number as a string
As everyone says pass it in as a string.
if php5 you can make sure it is string going in by casting
$zipcode = (string) $zipcode;
or
$zipcode = "$zipcode";
function is_zipcode_valid( $zipcode){
is_string($zipcode) //returns true
}
See Php.Net
Note: Instead of casting a variable to a string , it is also possible to enclose the variable in double quotes.
//create zipcode from number function
function form_zipcode($zipcode,$desiredLength){
if(str_len($zipcode) != $desiredLength)
{
return str_pad($zipcode,$desiredLength,"0",STR_PAD_LEFT);
}
else
{
return $zipcode;
}
}
Using form_zipcode(55,5) would return "00055";
Sorry typo last night (GMT here)
<?php
echo form_zipcode("55",5);
function form_zipcode($zipcode,$desiredLength){
if(strlen($zipcode) != $desiredLength)
{
return str_pad($zipcode,$desiredLength,"0",STR_PAD_LEFT);
}
else
{
return $zipcode;
}
}
?>
Works as expected returns 00055 That not what you require??
精彩评论