Friday, September 20, 2013

what are data type in php ?

PHP data types

In this part of the PHP tutorial, we will talk about data types.
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients. Tools to work with various data types are essential part of a modern computer language. According to the wikipedia definition, a data type is a set of values, and the allowable operations on those values.
PHP has eight data types:
Scalar types
  • boolean
  • integer
  • float
  • string
Compound types
  • array
  • object
Special types
  • resources
  • NULL
Unlike in languages like Java, C or Visual Basic, in PHP you do not provide an explicit type definition for a variable. A variable's type is determined at runtime by PHP. If you assign a string to a variable, it becomes a string variable. Later if you assign an integer value, the variable becomes an integer variable.

Boolean values

There is a duality built in our world. There is a Heaven and Earth, water and fire, jing and jang, man and woman, love and hatred. In PHP the boolean data type is a primitive data type having one of two values: True or False. This is a fundamental data type. Very common in computer programs.
Happy parents are waiting a child to be born. They have chosen a name for both possibilities. If it is going to be a boy, they have chosen John. If it is going to be a girl, they have chosen Victoria.
<?php

$male = False;

$r = rand(0, 1);

$male = $r ? True: False;

if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}
?>
The script uses a random integer generator to simulate our case.
$r = rand(0, 1);
The rand() function returns a random number from the given integer boundaries. In our case 0 or 1.
$male = $r ? True: False;
We use the ternary operator to set a $male variable. The variable is based on the random $r value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable is set to False.
if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}
We print the name. The if command works with boolean values. If the variable $male is True, we print the "We will use name John" to the console. If it has a False value, we print the other string.
The following script shows some common values that are considered to be True or False. For example, empty string, empty array, 0 are considered to be False.
<?php
class Object {};

var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) -1);
var_dump((bool) "PHP");
var_dump((bool) array(32));
var_dump((bool) array());
var_dump((bool) "false");
var_dump((bool) new Object());
var_dump((bool) NULL);
?>
In this script, we inspect some values in a boolean context. The var_dump() function shows information about a variable. The (bool) construct is called casting. In its casual context, the 0 value is a number. In a boolean context, it is False. The boolean context is when we use (bool) casting, when we use certain operators (negation, comparison operators) and when we use if/else, while keywords.
$ php boolean.php
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
Here is the outcome of the script.

Integers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.
In computer languages, integers are primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms.
Integers can be specified in three different notations in PHP. Decimal, hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x.
<?php

$var1 = 31;
$var2 = 031;
$var3 = 0x31;

echo "$var1\n";
echo "$var2\n";
echo "$var3\n";

?>
We assign 31 to three variables using three notations. And we print them to the console.
$ php notation.php 
31
25
49
The default notation is the decimal. The script shows these three numbers in decimal.
Integers in PHP have a fixed maximum size. The size of integers is platform dependent. PHP has built-in constants to show the maximum size of an integer.
$ uname -mo
i686 GNU/Linux
$ php -a
Interactive shell

php > echo PHP_INT_SIZE;
4
php > echo PHP_INT_MAX;
2147483647
php > 
On my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer value is 2147483647.
In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow happens. PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have greater boundaries.
<?php

$var = PHP_INT_MAX;

echo var_dump($var);
$var++;
echo var_dump($var);

?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And we compare the contents.
$ php boundary.php 
int(2147483647)
float(2147483648)
As we have mentioned previously, internally, the number becomes a floating point value.
In Java, the value after increasing would be -2147483648. This is where the term integer overflow comes from. The number goes over the top and becomes the smallest negative integer value assignable to a variable.
If we work with integers, we deal with discrete entities. We would use integers to count apples.
<?php

# number of baskets
$baskets = 16;

# number of apples in each basket 
$apples_in_basket = 24;

# total number of apples
$total = $baskets * $apples_in_basket;

echo "There are total of $total apples \n";
?>
In our script, we count the total amount of apples. We use the multiplication operation.
$ php apples.php 
There are total of 384 apples 
The output of the script.

Floating point numbers

Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities. Like weight, height or speed. Floating point numbers in PHP can be larger than integers and they can have a decimal point. The size of a float is platform dependent.
We can use various syntax to create floating point values.
<?php

$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);

?>
In this example, we have two cases of notations, that are used by scientists to denote floating point values. Also the $d variable is assigned a large number, so it is automatically converted to float type.
$ php floats.php 
float(1.245)
float(1200)
float(2.0E-10)
float(1264275425340000)
This is the output of the above script.
According to the documentation, floating point numbers should not be tested for equality. We will show an example why.
$ php -a
Interactive shell

php > echo 1/3;
0.333333333333
php > $var = (0.333333333333 == 1/3);
php > var_dump($var);
bool(false)
php > 
In this example, we compare two values that seem to be identical. But they yield unexpected result.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
<?php

# 100m is 0.1 km

$distance = 0.1;

# 9.87s is 9.87/60*60 h

$time = 9.87 / 3600;

$speed = $distance / $time;

echo "The average speed of a sprinter is $speed \n";

?>
In this example, it is necessary to use floating point values.
$speed = $distance / $time;
To get the speed, we divide the distance by the time.
$ php sprinter.php 
The average speed of a sprinter is 36.4741641337 
This is the output of the sprinter script. 36.4741641337 is a floating point number.

Strings

String is a data type representing textual data in computer programs. Probably the single most important data type in programming.
Since string are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.
<?php

$a = "PHP ";
$b = 'PERL';

echo $a, $b;
echo "\n";

?>
We can use single quotes and double quotes to create string literals.
$ php strings.php 
PHP PERL
The script outputs two strings to the console. The \n is a special sequence, a new line. The effect of this character is like if you hit the enter key when typing text.

Arrays

Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. In PHP, arrays are more diverse. Arrays can be treated as arrays, lists or dictionaries. In other words, arrays are all what in other languages we call arrays, lists, dictionaries.
Because collections are very important in all computer languages, we dedicate two chapters to collections - arrays. Here we show only a small example.
<?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

?>
The array keyword is used to create a collection of elements. In our case we have names. The print_r function prints a human readable information about a variable to the console.
$ php init.php 
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)
Output of the script. The numbers are indeces by which we can access the names.

Objects

So far, we have been talking about built-in data types. Objects are user defined data types. Programmers can create their data types that fit their domain. More about objects in chapter about object oriented programming, OOP.

Resources

Resources are special data types. They hold a reference to an external resource. They are created by special functions. Resources are handlers to opened files, database connections or image canvas areas.

NULL

There is another special data type - NULL. Basically, the data type means non existent, not known or empty.
In PHP, a variable is NULL in three cases:
  • it was not assigned a value
  • it was assigned a special NULL constant
  • it was unset with the unset() function
<?php

$a;
$b = NULL;

$c = 1;
unset($c);

$d = 2;

if (is_null($a)) echo "\$a is null\n";
if (is_null($b)) echo "\$b is null\n";
if (is_null($c)) echo "\$c is null\n";
if (is_null($d)) echo "\$d is null\n";

?>
In our example, we have four variables. Three of them are considered to be NULL. We use the is_null() function to determine, if the variable is NULL.
$ php null.php 
$a is null
$b is null
$c is null
Outcome of the script.

Type casting

We often work with multiple data types at once. Converting one data type to another one is a common job in programming. Type conversion or typecasting refers to changing an entity of one data type into another. There are two types of conversion. Implicit and explicit. Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.
php > echo "45" + 12;
57
php > echo 12 + 12.4;
24.4
In the above example, we have two examples of implicit type casting. In the first statement, the string is converted to integer and added to the second operand. If either operand is a float, then both operands are evaluated as floats, and the result will be a float.
Explicit conversion happens, when we use the cast constructs, like (boolean).
php > $a = 12.43;
php > var_dump($a);
float(12.43)
php > $a = (integer) $a;
php > var_dump($a);
int(12)
php > $a = (string) $a;
php > var_dump($a);
string(2) "12"
php > $a = (boolean) $a;
php > var_dump($a);
bool(true)
This code snippet shows explicit casting in action. First we assign a float value to a variable. Later we cast it to integer, string and finally boolean data type.

Wednesday, September 18, 2013

What is the difference between == and === in PHP?

When comparing values in PHP for equality you can use either the == operator or the === operator. What’s the difference between the 2? Well, it’s quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).

An example of when you need to use the === operator in PHP


It’s good to know the difference between the 2 types of operators that check for equality. But, it’s even better to understand when and why you would need to use the === operator versus the == operator. So, we want to give you an example of when you must use the === operator: When developing in PHP, you may find a time when you will need to use the strpos function – you should read more about this function here in order to understand our example (don’t worry it’s a very quick read).
When using the strpos function, it may return 0 to mean that the string you are searching for is at the 0th index (or the very first position) of the other string that you are searching. Suppose, for whatever reason, we want to make sure that an input string does not contain the string “xyz”. Then we would have this PHP code:
//bad code:
if ( strpos( $inputString, 'xyz' ) == false ) {
  
    // do something
 }

But, there is a problem with the code above: Because $strpos will return a 0 (as in the 0th index) if the $strpos variable happens to have the ‘xyz’ string at the very beginning of $inputString. But, the problem is that a 0 is also treated as false in PHP, and when the == operator is used to compare 0 and false, PHP will say that the 0 and false are equal. That is a problem because it is not what we wanted to have happen – even though the $inputString variable contains the string ‘xyz’, the equality of 0 and false tells us that $inputString does not contain the ‘xyz’ string. So, there is a problem with the way the return value of strpos is compared to the boolean value of ‘false’. But, what is the solution? Well, as you probably guessed, we can simply use the === operator for comparison. And, as we described earlier, the === operator will say that the 2 things being compared are equal only if both the type and value of the operands are also equal. So, if we compare a 0 to a false, then they will not be considered equal – which is exactly the kind of behavior we want. Here is what the good code will look like:
//good code:
if ( strpos( $inputString, 'xyz' ) === false ) {
  
    // do something
 }