Php function integer parameter problem

function is_zipcode_valid($zipcode){ ... }

      

if i call this function using is_zipcode_valid(08004);

my parameter 08004 is in number 8004, basically it removes all 0 obstacles.

How can I get around this problem?

thanks

+2


a source to share


4 answers


Pass it as a string and modify your function to expect a string:

is_zipcode_valid('08004');

      



Can't store leading zeros when using integers. If an integer value has a leading zero, it is interpreted in base 8. Here's an example:

echo 010; // Output is 8.

      

+3


a source


PHP treats integers as base8 numbers if a major zero is present. Pass your number asstring



0


a source


As everyone says, pass it as a string.

if php5 you can make sure it is a string by typing

$zipcode = (string) $zipcode; 

      

or

$zipcode = "$zipcode"; 




  function is_zipcode_valid( $zipcode){ 

   is_string($zipcode) //returns true
 }

      

See Php.Net

Note. Instead of casting the variable to a string, you can also enclose the variable in double quotes.

// create zipcode from numeric 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) will return "00055";

0


a source


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. 00055 Isn't that what you want?

0


a source







All Articles