PHP

Variables and data types

Variables are containers for storing information. Variables in PHP are identified by a dollar sign ($) followed by the variable name. Variables don't need to be declared, and they have no type until they are assigned a value. A variable name must begin with a letter or the underscore character and can only contain alphanumeric characters and underscores. A variable name cannot contain spaces. Finally, variable names in PHP are case sensitive.

The following code fragment shows a variable $var assigned the value of an expression, the Integer 15. Therefore, $var is defined as being of type integer.

$var = 15;

Because the variable in this example is used by assigning a value to it, it's implicitly declared. Variables in PHP are simple: when they are used, the type is implicitly defined-or redefined-and the variable implicitly declared. The variable type can change over the lifetime of the variable. Consider an example:

//Example
$var = 15;
$var = "Cat";

This fragment is acceptable in PHP. The type of $var changes from integer to string as the variable is reassigned. Letting PHP change the type of a variable as the context changes is very flexible and a little dangerous. For example, suppose that you have created code to manipulate an array variable. If the variable in question instead contains a number value and no array structure is in place, errors will occur when the code attempts to perform array-specific operations on the variable.

Variable names are case-sensitive in PHP, so $Variable, $variable, $VAriable, and $VARIABLE are all different variables.

When to Use Quotes

If you look closely at the PHP code block in above example, you'll notice that the value assigned to the first variable isn't enclosed in quotes. It looks like this:

$var = 15;

Then the "Cat" did use quotes, like this:

$var = "Cat";

The simple rules are as follows:

  • Text requires quotes
  • No quotes requires for numbers, True, False and Null

As a general principle, it doesn't matter whether you use single or double quotes around text or a string, as text is called in PHP and other computer languages.

Data Types

Different types of data take up different amounts of memory and may be treated differently when they are manipulated by a script. Some programming languages, such as Java, therefore demand that the programmer declare in advance which type of data a variable will contain.

By contrast, PHP is loosely typed, meaning that it automatically determines the data type at the time data is assigned to each variable. It means a variable can hold an integer and then later in the script it can hold a string or some other data type (See above example).

PHP has four scalar types: boolean, float, integer, and string, two compound types: array and object, and two special types: resource and null.

  • Scalar types:
    Variables of a scalar type can contain a single value at any given time. Scalar values can't break into smaller pieces.

    1. string - text (a collection of characters)
    2. boolean - true or false
    3. float (or double) - a floating point number
    4. integer - a whole number
  • Compound types:
    Variables of a compound type are made up of multiple scalar values or other compound values.

    1. array - an ordered set of keys and values
    2. object - an instance of a class
  • Special types:
    1. resource
      holding a reference to an external resource (database link, or a file stream etc.).
    2. null
      represents a variable with no value

String

You've already seen examples of strings earlier, when echo( ) and print( ) were introduced, and string literals are covered further in next sections. Consider two example string variables:

$variable = "This is a string";
$test = 'This is also a string';

PHP can create double and single-quoted string literals. If double quotation marks are needed as part of a string, the easiest approach is to switch to the single-quotation style:

echo 'This works';
echo "just like this.";
// And here are some strings that contain quotes
echo "This string has a ': a single quote!";
echo 'This string has a ": a double quote!';

Escaping Quotation Marks

Quotation marks can be escaped like this:

echo "This string has a \": a double quote!";
echo 'This string has a \': a single quote!';

One of the convenient features of PHP is the ability to include the value of a variable in a string literal. PHP parses double-quoted strings and replaces variable names with the variable's value. The following example shows how:

$number = 45;
$vehicle = "bus";
$message = "This $vehicle holds $number people";
// prints "This bus holds 45 people"
echo $message;

To include backslashes and dollar signs in a double-quoted string, the escaped sequences \\ and \$ can be used.

"a string with a \\ and a \$variable"

The single-quoted string isn't parsed in the same way as a double-quoted string and can print strings such as:

'a string with a \ and a $variable'

Joining Strings Together

PHP uses a period, dot, or full stop (.) as concatenation operator for joining strings:

$hello = 'Hello,';
$world = 'World';
echo $hello . $world; // Hello,World

When two strings are joined like this, PHP leaves no gap between them. Don't be fooled into thinking that adding a space after the period will do the trick. It won't. You can put as much space on either side of the period as you like; the result will always be the same, because PHP ignores whitespace in code. In fact, it's recommended to leave a space on either side of the period for readability.

To display a space in the final output, you must either include a space in one of the strings or insert the space as a string in its own right, like this:

echo $hello . ' ' . $world; // Hello, World

You also can create string using special heredoc or nowdoc syntax.

Boolean

Boolean variables are as simple as they get: they can be assigned either true or false. Here are two example assignments of a Boolean variable:

$variable = false;
$test = true;

Integer

An integer is a whole number, while a float is a number that has an exponent and a fractional part. The number 123.01 is a float, and so is 123.0. The number 123 is an integer. Consider the following two examples:

// This is an integer
$var1 = 6;
// This is a float
$var2 = 6.0;

Float (or double)

A float can also be represented using an exponential notation:

// This is a float that equals 1120
$var3 = 1.12e3;
// This is also a float that equals 0.02
$var4 = 2e-2

Arrays

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

$array = array(
         'one'   => 'Apple',
         'two'   => 'Mango',
         'three' => 'Banana'
        );

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

$array = [
         'one'   => 'Apple',
         'two'   => 'Mango',
         'three' => 'Banana'
        ];

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key:

$array = [
         'Apple',
         'Mango',
         'Banana'
        ];
        
// OR
$array2 = array(
         'Apple',
         'Mango',
         'Banana'
        );

We'll discuss the Arrays in more detail later in Arrays section.

Objects

An object is an instance of a class. To create a new object, we usually use the new statement to instantiate a class.

$anObject = new stdClass();

stdClass is PHP's generic empty class. It is useful for anonymous objects, dynamic properties, etc. we'll discuss the Classes later in the Classes section.

Resource

A resource is a special variable, holding a reference to an external resource. For example, open, read or create a file, connection or link to databases, ftp streams, file or directory handle etc.

Each resource can be access, modify or close by their own special functions. For example, to open and close a directory resource we use:

$dir = opendir('/path/to/dir');
//$dir handle holds the external resource

closedir($dir);
//freed the resource

Null

The null is used to represent a variable with no value. Such a variable is considered to be of the special null data type.

$var = null; // variable is set to null

In PHP, it is possible to use variables that have not been assigned a value. Such undefined variables are then automatically created with the null value.

echo $undefinedVar; // variable is set to null 

Note: PHP issues an error notice when undefined variables are used. Depending on the PHP error reporting settings, this message may or may not be displayed.

Iterables

Iterable, introduced in PHP 7.1, accepts any array or object implementing the Traversable interface (to detect if a class is traversable using foreach). Both of these types are iterable using foreach and can be used with yield from within a generator.

Iterable can be used as a parameter type to indicate that a function requires a set of values. If a value is not an array or instance of Traversable, a TypeError will be thrown:

<?php
function itrableFunc(iterable $iterable) {
 foreach ($iterable as $value) {
  echo $value.' ';
 } 
}

$arr = ['a','b','c'];
itrableFunc($arr);
//a b c

$str = 'hello';
itrableFunc($str);
//Fatal error: Uncaught TypeError...

Callbacks / Callables

Some functions like usort() or array_map() accept user-defined callback functions as a parameter. Callback functions can be:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().

Callback function example:

function callBack($p){
 return $p * 2;
}

function func($arr, $cb){
 foreach ($arr as $v){
  echo $cb($v)." ";
 }
}
$a = [1,2,5];
func($a, 'callBack');
//2 4 10

Callback example using a Closure:

function func($arr, $cb){
 foreach ($arr as $v){
  echo $cb($v)." ";
 }
}

$a = [1,2,5];
func($a, function ($p){
 return $p * 2;
});
//2 4 10

Data type examples

//Integer
$intg  = 1;
$intg2 = -2;

//Float
$flt  = 1.0;
$flt2 = -2.1;

//Boolean
$bol  = true;
$BOL  = TRUE;
$bol2 = false;
$bol3 = FALSE;

//String
$str  = 'A string';
$str2 = "Another string";
$str3 = '1';
$str4 = '2.0';
$str5 = "-2";
$str6 = 'true';
$str7 = "false";

//Null
$varNull = null;
$VARnull = NULL;

Note: true, false and null are case-insensitive constants, to recap, don't enclose them in quotes. The constants are discussed in next tutorial.

Advertisement:
Advertisement: