PHP - Data Types
Here’s a large block of code with examples for most data types. PHP is a dynamically typed language, meaning that you can assign values of different types to the same variable reference at different points in your control flow.
Note that var_dump() is used frequently in this example to show the variables of different types, as echo and print() are only capable of outputting strings, numbers, and booleans (where true is cast to 1 and false is cast to 0). var_dump() is great for debugging.
<?php# string$x = "words";var_dump($x);# int$x = 10;var_dump($x);# float$x = 10.1;var_dump($x);# boolean$x = true;var_dump($x);# array$x = array("alice", "bob", "charlie");var_dump($x);# objectclass Car { public $color; public $model; public function __construct($color, $model) { $this->color = $color; $this->model = $model; } public function message() { return "My car is a " . $this->color . " " . $this->model . "!\n"; }}
$myCar = new Car("red", "Volvo");var_dump($myCar);echo($myCar->message());# null$x = null;var_dump($x);?>Output of php datatypes.php:
string(5) "words"int(10)float(10.1)bool(true)array(3) { [0]=> string(5) "alice" [1]=> string(3) "bob" [2]=> string(7) "charlie"}object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo"}My car is a red Volvo!NULLTypecasting and Strings
Section titled “Typecasting and Strings”If you want to type cast to a different type, this is the syntax:
<?php$some_int = 5$im_a_string_now = (string) $some_int?>If you want to concatenate (combine) strings, use the dot operator:
<?php$combine = "hello" . " " . "world"?>