PHP data types
Data types specify the size and type of values that can be stored.
Output :
100
Data types specify the size and type of values that can be stored.
Variable does not need to be declared ITS DATA TYPE
adding a value to it.
PHP is a Loosely Typed Language so here no need to
define data type.
Example
:-
(variable
contains integer, float, and string value)
<?php
$num=100;
$fnum=100.0;
$str="Hello";
?>
Data types in PHP
There
are 3 types of DATA TYPE
Scalar/predefined
Compound/user-defined
Special type
Scalar(It holds only single value)
Integer:-
Integer means numeric data types. A
whole number with no fractional component.
Integer may be less than greater than or equal
to zero.
Example:-
<?php
$num=100;
echo $num;
?>
Boolean:-
Boolean are the
simplest data type. Like a switch that has only two states ON means true(1) and
OFF means false(0).
Example:-
<?php
$true=true;
$false=false;
var_dump($true,$false);
?>
Output : bool(true) bool(false)
Float:-
It is also
called numeric data
types. A number with a fractional component.
Example:-
<?php
$num=100.0;
echo $num;
?>
Output : 100.0
$num hold
value=100.0. pass $num inside echo statement to display the output.
String:-
Non numeric data type
String can hold letters,numbers and special
characters.
String value must be enclosed eighter in single
quotes or double
quotes.
Example:-
<?php
$str="Welcome
user";
$str1='how r you?';
$str2="@";
echo $str;
echo $str1;
echo $str2;
?>
Output : Welcome user
how r you?
@
Compound(Multiple values in single variable)
Array
<?php
$arr=array(10,20,30,40,50);
echo $arr[0];
?>
Output : 10
In the above
example
Variable( $arr) hold values an array . Now we want to print the first element of an array.
Then we pass variable($arr) name with index value[0], fetch the first element corresponding to the index value. Output will 10
Variable( $arr) hold values an array . Now we want to print the first element of an array.
Then we pass variable($arr) name with index value[0], fetch the first element corresponding to the index value. Output will 10
Object
<?php
class Demo()
{
public function
show()
{
echo "This
is show method<br/>";
}
}
$obj= new Demo();
$obj->show();
$obj->show();
?>
Output : This is show method
This is show
method
Special(2 types)
Null
Resource
Example:-
<?php
$blank=null;
var_dump($blank);
?>
Output :
NULL
Predefine function to Check data types
is_int( ) : Check given value is integer or not
is_float( ) : Check given value is float or not
is_numeric( )
: Check
given value is either integer or float
is_string( ) : Check given value is string or not
is_bool( ) : Check given value is Boolean or not
is_array( ) : Check given value is array or not
is_object( ) : Check given value is object or not
Check if given variable holds a integer type of value then
print the sum otherwise show error message
<?php
$x = 1000;
$y = 500;
if(is_int($x) && is_int($y))
{
$sum = $x + $y;
echo "sum =
".$sum;
}
else
{
echo "both
number must be integer";
}
?>
Output : sum = 1500