PHP var types

Deze site legt goed uit wat je met bepaalde type vars kan werken.
Welke automatisch worden geconverteerd etc etc.. hier even wat snippets..

Determining a Variable’s Type

Before passing a variable to a string function, you might want to determine whether it really is a string. PHP’s is_string function returns true or false to indicate whether the value passed to it is a string or not:

$val = '44';
if ( is_string($val) ) {
    echo 'string';
} else {
    echo 'not a string';
// string

PHP also provides functions for determining other types, including: is_intis_arrayis_boolis_float, and is_object.

Setting a Variable’s Type and Type Casting

PHP provides a variety of methods for changing the type of a variable or temporarily changing the type of the value it holds.

The settype Function

You can change the type of a variable by using PHP’s settype function. For example, suppose you have a variable that is currently assigned a number and you would like to convert it to a string. You can do so as follows:

$val = 24; // integer
// set $val type to string
settype($val, 'string');
// check type and value of $val
var_dump($val); // string(2) "24"

The variable will retain that type unless you either change the value of the variable to another type, or use settype again to assign another type to it. You can use the settype function to set the following types in addition to string: integer, float, boolean, array, object, and null.

Type Conversion Functions

PHP provides several functions that can be used to convert a value to a specific type. For example, the strval function can be used to convert a value to a string as we demonstrate here:

$val = 88; // integer
// pass $val to strval and check return value with var_dump
var_dump( strval($val) ); // string(2) "88"
// check type and value of $val
var_dump($val); // int(88) 

Geef een antwoord

Het e-mailadres wordt niet gepubliceerd.

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.