Thursday, February 24, 2011

Useful function for variable

gettype()
   gettype() determines the variable datatype and returns it. e.g. integer, float, string
if(gettype ($user_input) == "integer"){
   echo $user_input;
}


settype()
   settype() explicitly set the variable datatype. If datatype could not be set then a false value returned.
if(settype ($user_input, "integer" ){
   echo "Variable conversion successful";
}
else{
   echo "Variable conversion failed";
}


isset() and unset()
   unset() is used to destroy a variable, freeing all the memory that is associated with the variable so it is then available again. The isset() function is used to determine whether a variable has been given a value. If a value has been set then it returns true.


empty()
   empty() is nearly the opposite of isset(). It returns true if the variable is not set, or has a value of zero or an empty string. Otherwise it returns false.

echo empty($new); // true

$new = 1;
echo empty($new); // false

$new = "";
echo empty($new); // true

$new = 0;
echo empty($new); // true

$new = "Buon giorno";
echo empty($new); // false

unset ($new);
echo empty($new); // true


The is...() functions
   The functions is_int(), is_integer(), and is_long() are all synonymous functions that determine whether a variable is an integer.
   is_double(), is_float(), and is_real() determine whether a variable is a double.
   is_string(), is_array(), and is_object() work similarly for their respective data types.
$ProductID = "432BB";
if (is_string ($ProductID)) {
   echo ("String");
}


The ...val() functions
PHP provides yet another way to explicitly set the data type of a variable: the intval(), doubleval(), and strval() functions. These functions cannot be used to convert arrays or objects.

No comments:

Post a Comment