php variable types code example

Example 1: php data types

<?php
/*
Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

1) String
2) Integer
3) Float (floating point numbers - also called double)
4) Boolean
5) Array
6) Object
7) NULL
8) Resource
*/
  
// PHP String
$x = "Hello world!";
echo $x;

//PHP Integer
$x = 5985;
var_dump($x);

//PHP Float
$x = 10.365;
var_dump($x);

//PHP Boolean
$x = true;
$y = false;

//PHP Array
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

//PHP Object
  class Car {
      function Car() {
          $this->model = "VW";
      }
  }

  // create an object
  $herbie = new Car();

  // show object properties
  echo $herbie->model;

//PHP NULL Value
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Example 2: php define variable type

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is 5   (integer)
settype($bar, "string");  // $bar is "1" (string)
?>

Example 3: PHP Data Types

<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

Example 4: what are the different types of PHP variables?

There are 8 data types in PHP which are used to construct the variables:
1. Integers - are whole numbers without a decimal point, like 4195.
2. Doubles - are floating-point numbers, like 3.14486 or 49.1.
3. Booleans - have only two possible values either true or false.
4. Null - is a special type that only has one value:Null.
5. Strings - are sequences of characters.
6. Arrays - are named and indexed collection of other values.
7. Objects - are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
8. Resources- are spacial varibles that hold references to resources external to PHP.

Tags:

Php Example