PHP language data types

Lecture



Scalar data types

" Binary data (boolean)
" Integers
" Floating point numbers (float)
" Strings

Mixed data types

" Arrays
" Arrays (Array) Functions for working with arrays and array operations.
" Arrays (Array) Functions for working with arrays and array operations. Part 2
" Some features of working with arrays
" Objects (Object)

Special data types

" Resources (Resource)
" Empty type (NULL)

Data Pseudo Types

" Mixed
" Numbers (Number)
" Callback

Additionally

" Data Type Manipulations

Number pseudotype

The pseudotype number says that the parameter can be either integer or float .

Types of data (variables) in PHP

PHP supports eight simple data types (variables):

Four scalar types :

  • boolean (binary data)
  • integer (integers)
  • float (floating point numbers or 'double')
  • string (strings)

Two mixed types :

  • array
  • object

And two special types :

  • resource
  • NULL ("empty" type)

There are also several pseudotypes :

  • mixed
  • number (numeric)
  • callback

Consider a briefly listed PHP data types.

Boolean type (binary data)

This is the simplest type. It expresses the truth of a value — it can be either TRUE or FALSE . Boolean type was introduced in PHP 4.

To define a boolean type, use the keyword TRUE or FALSE . Both are case-independent.

$x = True; // присвоить $x значение TRUE
?>

Usually you use a certain operator that returns a logical expression and then transmits it to the control structure.

// == это оператор, который проверяет
// эквивалентность и возвращает булево значение
if ($action == "показать_версию") {
echo "Версия 1.23";
}

// это не обязательно...
if ($show_separators == TRUE) {
echo "


\n";
}

// ...потому что вы можете просто написать
if ($show_separators) {
echo "

\n";
}
?>

Read more about boolean data types here .

Type integer (integers)

An integer is a number from the set Z = {..., -2, -1, 0, 1, 2, ...}, usually 32 bits long (from –2,147,483,648 to 2,147,483,647).

Integers can be specified in decimal, hexadecimal or octal number systems, optionally with a preceding (- or +) sign.

If you are using the octal number system, you must precede the number 0 (zero), to use the hexadecimal system, you must put it in front of the number 0x .

$a = 1234; // десятичное число
$a = -123; // отрицательное число
$a = 0123; // восьмеричное число (эквивалентно 83 в десятичной системе)
$a = 0x1A; // шестнадцатеричное число (эквивалентно 26 в десятичной системе)
?>

More about data types integer see here .

Type float (floating point numbers)

Double - a real number of fairly high accuracy (it should be enough for the vast majority of mathematical calculations).

Floating-point numbers (double-precision numbers or real numbers) can be defined using any of the following syntaxes:

$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>

More about data types float see here .

Type string (strings)

A string in PHP is a set of characters of any length. Unlike C, strings can also contain null characters, which does not affect the program. In other words, strings can be used to store binary data. The length of the string is limited only by the size of the freedom of RAM.

A string can be easily processed using standard functions, you can also directly refer to any of its characters.

Example of a string variable:


$ a = "Это просто текст, записанный в строковую переменную" ;
echo $ a ; //Выводит 'Это просто текст, записанный в строковую переменную'
?>

More about data types string see here .

Type array

An array in PHP is an ordered set of data in which the correspondence between the value and the key is established .

The index (key) is used to uniquely identify the element inside the array. In the same array can not be two elements with the same index.

PHP allows you to create arrays of any complexity. Consider some examples:

Simple array (list)

Arrays whose indexes are numbers starting with zero are lists:

php
// Простой способ инициализации массива
$ names [ 0 ]= "Апельсин" ;
$ names [ 1 ]= "Банан" ;
$ name s[ 2 ]= "Груша" ;
$ names [ 3 ]= "Помидор" ;
// Здесь: names - имя массива, а 0, 1, 2, 3 - индексы массива
?>

Associative arrays

In PHP, an array index can be not only a number, but also a string. And there are no restrictions on the string: it can contain spaces, special characters and be of any length.

Arrays whose indexes are strings are called associative arrays. Associative array indices are called keys. An example of an associative array:

php
// Ассоциативный массив
$ names [ "Иванов" ]= "Иван" ;
$ names [ "Сидоров" ]= "Николай" ;
$ name s[ "Петров" ]= "Петр" ;
// В данном примере: фамилии - ключи ассоциативного массива
// , а имена - элементы массива
?>

Multidimensional arrays

To create arrays in PHP, there is a special instruction array () . It is convenient to use to create multidimensional arrays . Let's give a specific example:

php
// Многомерный массив
$ A [ "Ivanov" ] = array ( "name" => "Иванов И.И." , "age" => "25" , "email" => " ivanov@mail.ru " );
$ A [ "Petrov" ] = array ( "name" => "Петров П.П." , "age" => "34" , "email" => " petrov@mail.ru " );
$ A [ "Sidorov" ] = array ( "name" => "Сидоров С.С." , "age" => "47" , "email" => " sidorov@mail.ru " );
?>

Multidimensional arrays are similar to Pascal entries or C structures.

You can learn more about arrays and array operations here.

Type object (s)

The object is one of the basic concepts of object-oriented programming. The internal structure of the object is similar to a hash, except that the operator -> , rather than square brackets, is used to access individual elements and functions.

To initialize an object, use the new expression, which creates an instance of an object in a variable.

class foo
{
function do_foo()
{
echo "Doing foo.";
}
}

$bar = new foo;
$bar->do_foo();
?>

Detailed consideration of objects is made in the section PHP and OOP

Resource type (resources)

A resource is a special variable containing a link to an external resource. Resources are created and used by special functions. For a complete list of these functions and corresponding resource types, see here .

Type NULL ("empty" type)

The special value NULL indicates that this variable does not matter. NULL is the only possible value of type NULL (empty type).

A variable is considered NULL if:

  • it was assigned the constant NULL ;

  • she has not yet been assigned any value;

  • it was removed with unset () .

$var = NULL;
?>

See also is_null () and unset () .

Mixed pseudotype

mixed says that a parameter can take many (but not necessarily all) types.

gettype () , for example, accepts all PHP types, whereas str_replace () accepts strings and arrays.

Pseudotype number (numeric)

The number indicates that the parameter can be either integer or float .

Pseudotype callback

Some functions, such as call_user_func () or usort (), accept user-defined callback functions as parameters. Callback functions can be not only simple functions, but also methods of objects, including static methods of classes.

The PHP function is simply passed as a string of its name. You can pass any built-in or user-defined function with the exception of array () , echo () , empty () , eval () , exit () , isset () , list () , print () and unset () .

Here are some examples of callback functions:


// простой пример callback
function my_callback_function() {
echo 'hello world!';
}
call_user_func('my_callback_function');

// примеры callback-метода
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}

// вызов метода статического класса без создания объекта
call_user_func(array('MyClass', 'myCallbackMethod'));

// вызов метода объекта
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>

We looked at some rather superficial PHP data types. For more information on this issue, visit the PHP Data Types subsection.

created: 2016-01-25
updated: 2021-03-13
132420



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)