PHP - Data Types

php

What are the four scalar types?

  1. boolean
  2. integer
  3. float (floating-point number, aka double)
  4. string

What are the 3 compound types available in PHP?

  1. array
  2. object
  3. callable

What the 2 special types available in PHP?

  1. resource
  2. NULL

What are some pseudo-types available in PHP?

  1. mixed
  2. number
  3. callback (aka callable)
  4. array|object
  5. void

Is the type of a variable typically set by the programmer?

No. The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

How can we determine the type of a variable?

To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:

$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}

// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}

How can we forcibly convert a variable to a certain type?

To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.

How does PHP handle NaN?

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License