Which function can we use to change the datatype of a variable in php?

[PHP 4, PHP 5, PHP 7, PHP 8]

settypeSet the type of a variable

Description

settype[mixed &$var, string $type]: bool

Parameters

var

The variable being converted.

type

Possibles values of type are:

  • "boolean" or "bool"
  • "integer" or "int"
  • "float" or "double"
  • "string"
  • "array"
  • "object"
  • "null"

Return Values

Returns true on success or false on failure.

Examples

Example #1 settype[] example

Notes

Note:

Maximum value for "int" is PHP_INT_MAX.

Special Notes

10 years ago

Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...

robin at barafranca dot com

14 years ago

Just a quick note, as this caught me out very briefly:

settype[] returns bool, not the typecasted variable - so:

$blah = settype[$blah, "int"]; // is wrong, changes $blah to 0 or 1
settype[$blah, "int"]; // is correct

Hope this helps someone else who makes a mistake.. ;]

sdibb at myway dot com

19 years ago

Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval[$string] does the same thing.

If you're looking for a security check, or to strip non-numeric characters [such as cleaning up phone numbers or ZIP codes],  try this instead:

nospamplease at veganismus dot ch

17 years ago

you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.

Anonymous

3 years ago

If you attempt to convert the special $this variable from an instance method [only in classes] :
* PHP will silently return TRUE and leave $this unchanged if the type was 'bool', 'array', 'object' or 'NULL'
* PHP will generate an E_NOTICE if the type was 'int', 'float' or 'double', and $this will not be casted
* PHP will throw a catchable fatal error when the type is 'string' and the class does not define the __toString[] method
Unless the new variable type passed as the second argument is invalid, settype[] will return TRUE. In all cases the object will remain unchanged.

Here is the result :
Type                 Succeed?             Converted
bool                 1                    Foo Object
[
]

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

int                  1                    Foo Object
[
]

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

float                1                    Foo Object
[
]

array                1                    Foo Object
[
]

object               1                    Foo Object
[
]

Warning: settype[]: Invalid type in C:\php\examples\oop-settype-this.php on line 14

unknowntype                               Foo Object
[
]

NULL                 1                    Foo Object
[
]

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString[] :

So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString[] method.

Hope this helps !  :]

DarkMaster

1 year ago

matt at mattsoft dot net

16 years ago

using [int] insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.

geoffsmiths at hotmail dot com

2 years ago

Please note:

When using settype to convert indexed arrays to objects, the properties of the typed object will be integers:

A brief example:

$a = ['1', '2'];

settype[$a, 'object'];

var_dump[$a];

// output
object[stdClass]#1 [2] {
  ["0"]=>
  string[1] "1"
  ["1"]=>
  string[1] "2"
}

Skayo

5 years ago

$foo = "1";
settype[$foo, "bool"];
var_dump[$foo]; // Outputs: bool[true]

$bar = "0";
settype[$bar, "bool"];
var_dump[$bar]; // Outputs: bool[false]

ludvig dot ericson gmail.dot com

16 years ago

To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func

ns at canada dot com

22 years ago

This settype[] behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "


2 $var = 'ciao';
3 $arr = [array] $var;
4 echo $arr[0];  // outputs 'ciao'

And if [like your code above] you do a settype on an empty variable, you'll end up with a one element array with an empty [not unset!] first element. So appeanding to it will start appending at index 1. As for why reset[] doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.

NWdev

13 years ago

In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.



The var_dumps both return the following:


The gettype echo will show the value as an integer.

So it seems that settype[$val,'int'] makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using

is not a option.

I resolved my array value conversion using this instead:

Thanks to the posting here:
//usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.

memandeemail at gmail dot com

17 years ago

/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject[&$values] {
        $values = [object] $values;
        foreach [$values as $tkey => $val] {
            if [is_array[$val]] {
                setobject[$val];
                $values->$tkey = $val;
            }
        }
        return [bool] $values;
    }

Michael Benedict

16 years ago

note that settype[] will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype[] call in a call to isset[].



prints "|0|", NOT "||".

To get the latter, use:

marjune

5 years ago

any digit except 0 or -0 are considered true in boolean, and any string except '0' or '' are also considered true.



This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.



In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if [boolean] $foo === false, it will throw an error unless $foo->bar is valid [i.e. $foo is an object already].

How do you change the type of data types in PHP?

The settype[] function is used to set the type of a variable. The variable being converted. Type of the variable. Possible values are : boolean, integer, float, string, array, object, null.

What is the use of Settype [] and Gettype [] function in PHP?

The gettype[] function gets the type of variable; gettype[] is a function that display a data type. The settype function sets the type of variable; the settype[] function changes the data type.

Which function is used for datatype and value in PHP?

The gettype[] function is an inbuilt function in PHP which is used to get the type of a variable. It is used to check the type of existing variable.

Which function can be used to know the data type of a variable?

We can use the type[] function to know which class a variable or a value belongs to.

Chủ Đề