PHP: settype() function
The settype() function is used to set the type of a variable.
Name | Description | Required / Optional | Type |
---|---|---|---|
var_name | The variable being converted. | Required | Mixed* |
var_type | Type of the variable. Possible values are : boolean, integer, float, string, array, object, null. | Optional | String |
*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value:
TRUE on success or FALSE on failure.
Value Type: Boolean.
Practice here online :
Previous: serialize
Next: strval
Follow us on Facebook and Twitter for latest update.
PHP: Tips of the Day
How to Sort Multi-dimensional Array by Value?
Try a usort, If you are still on PHP 5.2 or earlier, you’ll have to define a sorting function first:
function sortByOrder($a, $b) < return $a['order'] - $b['order']; >usort($myArray, 'sortByOrder');
Starting in PHP 5.3, you can use an anonymous function:
And finally with PHP 7 you can use the spaceship operator:
usort($myArray, function($a, $b) < return $a['order'] $b['order']; >);
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero — best explained below. You can also use this for sorting on sub-elements.
usort($myArray, function($a, $b) < $retval = $a['order'] $b['order']; if ($retval == 0) < $retval = $a['suborder'] $b['suborder']; if ($retval == 0) < $retval = $a['details']['subsuborder'] $b['details']['subsuborder']; > > return $retval; >);
If you need to retain key associations, use uasort() — see comparison of array sorting functions in the manual
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
PHP settype() Function
The settype() function converts a variable to a specific type.
Syntax
Parameter Values
Parameter | Description |
---|---|
variable | Required. Specifies the variable to convert |
type | Required. Specifies the type to convert variable to. The possible types are: boolean, bool, integer, int, float, double, string, array, object, null |
Technical Details
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
settype
Returns true on success or false on failure.
Examples
Example #1 settype() example
$foo = «5bar» ; // string
$bar = true ; // boolean
?php
settype ( $foo , «integer» ); // $foo is now 5 (integer)
settype ( $bar , «string» ); // $bar is now «1» (string)
?>
Notes
Note:
Maximum value for «int» is PHP_INT_MAX .
See Also
User Contributed Notes 17 notes
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.
$var = «true» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true
$var = «false» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true as well!
$var = «» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // false
?>
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.. 😉
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:
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.
/*
This example works 4x faster than settype() function in PHP-CGI 5.4.13 and
8x faster in PHP-CGI 7.1.3(x64) for windows
*/
?php
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.
// This was tested with PHP 7.2
class Foo function test () printf ( «%-20s %-20s %s\n» , ‘Type’ , ‘Succeed?’ , ‘Converted’ );
// settype() should throw a fatal error, as $this cannot be re-assigned
printf ( «%-20s %-20s %s\n» , ‘bool’ , settype ( $this , ‘bool’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘int’ , settype ( $this , ‘int’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘float’ , settype ( $this , ‘float’ ), print_r ( $this ));
printf ( «%-20s %-20s %s\n» , ‘array’ , settype ( $this , ‘array’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘object’ , settype ( $this , ‘object’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘unknowntype’ , settype ( $this , ‘unknowntype’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘NULL’ , settype ( $this , ‘NULL’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘string’ , settype ( $this , ‘string’ ), print_r ( $this , TRUE ));
>
>
$a = new Foo ();
$a -> test ();
?>
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
Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10
Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14
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() :
class Foo // .
function __toString () return ‘Foo object is awesome!’ ;
>
// .
>
?>
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.
Php set value type
Для получения типа переменной применяется функция gettype() , которая возвращает название типа переменной, например, integer (целое число), double (число с плавающей точкой), string (строка), boolean (логическое значение), null , array (массив), object (объект) или unknown type . Например:
Также есть ряд специальных функций, которые возвращают true или false в зависимости от того, представляет ли переменная определенный тип:
- is_integer($a) : возвращает значение true , если переменная $a хранит целое число
- is_string($a) : возвращает значение true , если переменная $a хранит строку
- is_double($a) : возвращает значение true , если переменная $a хранит действительное число
- is_numeric($a) : возвращает значение true , если переменная $a представляет целое или действительное число или является строковым представлением числа. Например:
$a = 10; $b = "10"; echo is_numeric($a); echo "
"; echo is_numeric($b);
Установка типа. Функция settype()
С помощью функции settype() можно установить для переменной определенный тип. Она принимает два параметра: settype(«Переменная», «Тип») . В качестве первого параметра используется переменная, тип которой надо установить, а в качестве второго — строковое описание типа, которое возвращается функцией gettype() .
Если удалось установить тип, то функция возвращает true , если нет — то значение false .
Например, установим для переменной целочисленный тип:
Поскольку переменная $a представляет действительное число 10.7, то его вполне можно преобразовать в целое число через отсечение дробной части. Поэтому в данном случае функция settype() возвратит true .
Преобразование типов
По умолчанию PHP при необходимости автоматически преобразует значение переменной из одного типа в другой. По этой причине явные преобразования в PHP не так часто требуются. Тем не менее мы можем их применять.
Для явного преобразования перед переменной в скобках указыется тип, в который надо выполнить преобразование:
$boolVar = false; $intVar = (int)$boolVar; // 0 echo "boolVar = $boolVar
intVar = $intVar";
В данном случае значение «false» пробразуется в значение типа int , которое будет храниться в переменной $intVar . А именно значение false преобразуется в число 0. После этого мы сможем использовать данное значение как число.
При использовании выражения echo для вывода на страницу передаваемые значения автоматически преобразуются в строку. И поскольку переменная boolVar равна false , ее значение будет преобазовано в пустую строку. Тогда как значение 0 преобразуется в строку «0».
В PHP могут применяться следующие преобразования:
- (int), (integer) : преобразование в int (в целое число)
- (bool), (boolean) : преобразование в bool
- (float), (double), (real) : преобразование в float
- (string) : преобразование в строку
- (array) : преобразование в массив
- (object) : преобразование в object