0% found this document useful (0 votes)
9 views40 pages

Bab 2 PHP

The document provides an overview of PHP data types, including strings, integers, floats, booleans, arrays, objects, NULL, and resources. It explains how to use the var_dump() function to determine data types and includes examples for each type. Additionally, it covers string manipulation functions and numeric types, including infinity and NaN.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Bab 2 PHP

The document provides an overview of PHP data types, including strings, integers, floats, booleans, arrays, objects, NULL, and resources. It explains how to use the var_dump() function to determine data types and includes examples for each type. Additionally, it covers string manipulation functions and numeric types, including infinity and NaN.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Bab 2 Data Types,

String, Numbers,
Casting, Math,
Constants

PHP Data Types

PHP Data Types


Variables can store data of different types, and different data
types can do different things.

PHP supports the following data types:

• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
Getting the Data Type
You can get the data type of any object by using the
var_dump() function.

Example
Get your own PHP Server
The var_dump() function returns the data type and the value:

$x = 5;
var_dump($x);

PHP String
A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or
double quotes:

Example
$x = "Hello world!";
$y = 'Hello world!';

var_dump($x);
echo "<br>";
var_dump($y);

PHP Integer
An integer data type is a non-decimal number between
-2,147,483,648 and 2,147,483,647.

Rules for integers:

• An integer must have at least one digit


• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10),
hexadecimal (base 16), octal (base 8), or binary (base 2)
notation
In the following example $x is an integer. The PHP var_dump()
function returns the data type and value:

Example
$x = 5985;
var_dump($x);

PHP Float
A float (floating point number) is a number with a decimal
point or a number in exponential form.

In the following example $x is a float. The PHP var_dump()


function returns the data type and value:

Example
$x = 10.365;
var_dump($x);

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

Example
$x = true;
var_dump($x);
Booleans are often used in conditional testing.
You will learn more about conditional testing in the PHP
If...Else chapter.

PHP Array
An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP


var_dump() function returns the data type and value:

Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
You will learn a lot more about arrays in later chapters of this
tutorial.

PHP Object
Classes and objects are the two main aspects of object-
oriented programming.

A class is a template for objects, and an object is an instance


of a class.

When the individual objects are created, they inherit all the
properties and behaviors from the class, but each object will
have different values for the properties.

Let's assume we have a class named Car that can have


properties like model, color, etc. We can define variables like
$model, $color, and so on, to hold the values of these
properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are


created, they inherit all the properties and behaviors from the
class, but each object will have different values for the
properties.

If you create a __construct() function, PHP will automatically


call this function when you create an object from a class.

Example
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");


var_dump($myCar);
Do not worry if you do not understand the PHP Object syntax,
you will learn more about that in the PHP Classes/Objects
chapter.

PHP NULL Value


Null is a special data type which can have only one value:
NULL.

A variable of data type NULL is a variable that has no value


assigned to it.

Tip: If a variable is created without a value, it is automatically


assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:


Example
$x = "Hello world!";
$x = null;
var_dump($x);

Change Data Type


If you assign an integer value to a variable, the type will
automatically be an integer.

If you assign a string to the same variable, the type will


change to a string:

Example
$x = 5;
var_dump($x);

$x = "Hello";
var_dump($x);
If you want to change the data type of an existing variable, but
not by changing the value, you can use casting.

Casting allows you to change data type on variables:

Example
$x = 5;
$x = (string) $x;
var_dump($x);
You will learn more about casting in the PHP Casting Chapter.

PHP Resource
The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to
PHP.

A common example of using the resource data type is a


database call.

We will not talk about the resource type here, since it is an


advanced topic.

PHP Strings
A string is a sequence of characters, like "Hello world!".

Strings
Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.

Example
Get your own PHP Server
echo "Hello";
echo 'Hello';
Note There is a big difference between double quotes and
single quotes in PHP.

Double quotes process special characters, single quotes does


not.

Double or Single Quotes?


You can use double or single quotes, but you should be aware
of the differences between the two.

Double quoted strings perform action on special characters.

E.g. when there is a variable in the string, it returns the value


of the variable:

Example
Double quoted string literals perform operations for special
characters:

$x = "John";
echo "Hello $x";
Single quoted strings does not perform such actions, it returns
the string like it was written, with the variable name:

Example
Single quoted string literals returns the string as it is:

$x = "John";
echo 'Hello $x';
String Length
The PHP strlen() function returns the length of a string.

Example
Return the length of the string "Hello world!":

echo strlen("Hello world!");

Word Count
The PHP str_word_count() function counts the number of
words in a string.

Example
Count the number of word in the string "Hello world!":

echo str_word_count("Hello world!");

Search For Text Within a String


The PHP strpos() function searches for a specific text within a
string.

If a match is found, the function returns the character position


of the first match. If no match is found, it will return FALSE.

Example
Search for the text "world" in the string "Hello world!":

echo strpos("Hello world!", "world");


Tip: The first character position in a string is 0 (not 1).
Complete PHP String Reference
For a complete reference of all string functions, go to our
complete PHP String Reference.

The PHP string reference contains description and example of


use, for each function!

PHP - Modify Strings


PHP has a set of built-in functions that you can use to
modify strings.

Upper Case
Example
Get your own PHP Server
The strtoupper() function returns the string in upper case:

$x = "Hello World!";
echo strtoupper($x);

Lower Case
Example
The strtolower() function returns the string in lower case:

$x = "Hello World!";
echo strtolower($x);

Replace String
The PHP str_replace() function replaces some characters
with some other characters in a string.

Example
Replace the text "World" with "Dolly":

$x = "Hello World!";
echo str_replace("World", "Dolly", $x);

Reverse a String
The PHP strrev() function reverses a string.

Example
Reverse the string "Hello World!":

$x = "Hello World!";
echo strrev($x);

Remove Whitespace
Whitespace is the space before and/or after the actual text,
and very often you want to remove this space.

Example
The trim() removes any whitespace from the beginning or the
end:

$x = " Hello World! ";


echo trim($x);
Learn more in our trim() Function Reference.

Convert String into Array


The PHP explode() function splits a string into an array.

The first parameter of the explode() function represents the


"separator". The "separator" specifies where to split the string.

Note: The separator is required.

Example
Split the string into an array. Use the space character as
separator:

$x = "Hello World!";
$y = explode(" ", $x);

//Use the print_r() function to display the result:


print_r($y);
/*
Result:
Array ( [0] => Hello [1] => World! )
*/

Complete PHP String Reference


For a complete reference of all string functions, go to our
complete PHP String Reference.

PHP - Concatenate
Strings

String Concatenation
To concatenate, or combine, two strings you can use the .
operator:

Example
Get your own PHP Server
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
The result of the example above is HelloWorld, without a
space between the two words.

You can add a space character like this:

Example
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
An easier and better way is by using the power of double
quotes.

By surrounding the two variables in double quotes with a white


space between them, the white space will also be present in
the result:

Example
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;

Complete PHP String Reference


For a complete reference of all string functions, go to our
complete PHP String Reference.
PHP - Slicing Strings

Slicing
You can return a range of characters by using the substr()
function.

Specify the start index and the number of characters you want
to return.

Example
Get your own PHP Server
Start the slice at index 6 and end the slice 5 positions later:

$x = "Hello World!";
echo substr($x, 6, 5);
Note The first character has index 0.

Slice to the End


By leaving out the length parameter, the range will go to the
end:

Example
Start the slice at index 6 and go all the way to the end:

$x = "Hello World!";
echo substr($x, 6);

Slice From the End


Use negative indexes to start the slice from the end of the
string:

Example
Get the 3 characters, starting from the "o" in world (index -5):

$x = "Hello World!";
echo substr($x, -5, 3);
Note The last character has index -1.

Negative Length
Use negative length to specify how many characters to omit,
starting from the end of the string:

Example
From the string "Hi, how are you?", get the characters starting
from index 5, and continue until you reach the 3. character
from the end (index -3).

Should end up with "ow are y":

$x = "Hi, how are you?";


echo substr($x, 5, -3);
Complete PHP String Reference

PHP - Escape Characters

Escape Character
To insert characters that are illegal in a string, use an escape
character.

An escape character is a backslash \ followed by the character


you want to insert.

An example of an illegal character is a double quote inside a


string that is surrounded by double quotes:

Example
Get your own PHP Server
$x = "We are the so-called "Vikings" from the north.";
To fix this problem, use the escape character \":

Example
$x = "We are the so-called \"Vikings\" from the north.";

Escape Characters
Other escape characters used in PHP:

Code Result Try


it
\' Single Quote

\" Double Quote

\$ PHP variables

\n New Line

\r Carriage Return

\t Tab

\f Form Feed

\ooo Octal value

\xhh Hex value


PHP Numbers
In this chapter we will look in depth into Integers, Floats,
and Number Strings.

PHP Numbers
There are three main numeric types in PHP:

• Integer
• Float
• Number Strings
In addition, PHP has two more data types used for numbers:

• Infinity
• NaN
Variables of numeric types are created when you assign a
value to them:

Example
Get your own PHP Server
$a = 5;
$b = 5.34;
$c = "25";
To verify the type of any object in PHP, use the var_dump()
function:

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

PHP Integers
2, 256, -256, 10358, -179567 are all integers.

An integer is a number without any decimal part.

An integer data type is a non-decimal number between


-2147483648 and 2147483647 in 32 bit systems, and between
-9223372036854775808 and 9223372036854775807 in 64 bit
systems. A value greater (or lower) than this, will be stored as
float, because it exceeds the limit of an integer.

Note: Another important thing to know is that even if 4 * 2.5


is 10, the result is stored as float, because one of the operands
is a float (2.5).

Here are some rules for integers:

• An integer must have at least one digit


• An integer must NOT have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (base
10), hexadecimal (base 16 - prefixed with 0x), octal (base
8 - prefixed with 0) or binary (base 2 - prefixed with 0b)
PHP has the following predefined constants for integers:
• PHP_INT_MAX - The largest integer supported
• PHP_INT_MIN - The smallest integer supported
• PHP_INT_SIZE - The size of an integer in bytes
PHP has the following functions to check if the type of a
variable is integer:

• is_int()
• is_integer() - alias of is_int()
• is_long() - alias of is_int()
Example
Check if the type of a variable is integer:

$x = 5985;
var_dump(is_int($x));

$x = 59.85;
var_dump(is_int($x));

PHP Floats
A float is a number with a decimal point or a number in
exponential form.

2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

The float data type can commonly store a value up to


1.7976931348623E+308 (platform dependent), and have a
maximum precision of 14 digits.

PHP has the following predefined constants for floats (from PHP
7.2):
• PHP_FLOAT_MAX - The largest representable floating point
number
• PHP_FLOAT_MIN - The smallest representable positive
floating point number
• PHP_FLOAT_DIG - The number of decimal digits that can
be rounded into a float and back without precision loss
• PHP_FLOAT_EPSILON - The smallest representable positive
number x, so that x + 1.0 != 1.0
PHP has the following functions to check if the type of a
variable is float:

• is_float()
• is_double() - alias of is_float()
Example
Check if the type of a variable is float:

$x = 10.365;
var_dump(is_ oat($x));

PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is
considered infinite.

PHP has the following functions to check if a numeric value is


finite or infinite:

• is_finite()
• is_infinite()
However, the PHP var_dump() function returns the data type
and value:

Example
Check if a numeric value is finite or infinite:

$x = 1.9e411;
var_dump($x);
fl
PHP NaN
NaN stands for Not a Number.

NaN is used for impossible mathematical operations.

PHP has the following functions to check if a value is not a


number:

• is_nan()
However, the PHP var_dump() function returns the data type
and value:

Example
Invalid calculation will return a NaN value:

$x = acos(8);
var_dump($x);

PHP Numerical Strings


The PHP is_numeric() function can be used to find whether a
variable is numeric. The function returns true if the variable is
a number or a numeric string, false otherwise.

Example
Check if the variable is numeric:

$x = 5985;
var_dump(is_numeric($x));

$x = "5985";
var_dump(is_numeric($x));
$x = "59.85" + 100;
var_dump(is_numeric($x));
$x = "Hello";
var_dump(is_numeric($x));
Note: From PHP 7.0: The is_numeric() function will return
FALSE for numeric strings in hexadecimal form (e.g.
0xf4c3b00c), as they are no longer considered as numeric
strings.

PHP Casting Strings and Floats


to Integers
Sometimes you need to cast a numerical value into another
data type.

The (int), (integer), and intval() functions are often


used to convert a value to an integer.

Example
Cast float and string to integer:

// Cast oat to int


$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;

echo "<br>";

// Cast string to int


$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
fl
PHP Casting
Sometimes you need to change a variable from one data
type into another, and sometimes you want a variable to
have a specific data type. This can be done with casting.

Change Data Type


Casting in PHP is done with these statements:

• (string) - Converts to data type String


• (int) - Converts to data type Integer
• (float) - Converts to data type Float
• (bool) - Converts to data type Boolean
• (array) - Converts to data type Array
• (object) - Converts to data type Object
• (unset) - Converts to data type NULL

Cast to String
To cast to string, use the (string) statement:

Example
Get your own PHP Server
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL

$a = (string) $a;
$b = (string) $b;
$c = (string) $c;
$d = (string) $d;
$e = (string) $e;

//To verify the type of any object in PHP, use the var_dump() function:
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);

Cast to Integer
To cast to integer, use the (int) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL

$a = (int) $a;
$b = (int) $b;
$c = (int) $c;
$d = (int) $d;
$e = (int) $e;
$f = (int) $f;
$g = (int) $g;

Cast to Float
To cast to float, use the (float) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL

$a = ( oat) $a;
$b = ( oat) $b;
$c = ( oat) $c;
$d = ( oat) $d;
$e = ( oat) $e;
$f = ( oat) $f;
$g = ( oat) $g;

Cast to Boolean
To cast to boolean, use the (bool) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = 0; // Integer
$d = -1; // Integer
$e = 0.1; // Float
$f = "hello"; // String
$g = ""; // String
$h = true; // Boolean
$i = NULL; // NULL

$a = (bool) $a;
$b = (bool) $b;
$c = (bool) $c;
$d = (bool) $d;
$e = (bool) $e;
$f = (bool) $f;
$g = (bool) $g;
fl
fl
fl
fl
fl
fl
fl
$h = (bool) $h;
$i = (bool) $i;
If a value is 0, NULL, false, or empty, the (bool) converts it into
false, otherwise true.

Even -1 converts to true.

Cast to Array
To cast to array, use the (array) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL

$a = (array) $a;
$b = (array) $b;
$c = (array) $c;
$d = (array) $d;
$e = (array) $e;
When converting into arrays, most data types converts into an
indexed array with one element.

NULL values converts to an empty array object.

Objects converts into associative arrays where the property


names becomes the keys and the property values becomes the
values:

Example
Converting Objects into Arrays:

class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");

$myCar = (array) $myCar;


var_dump($myCar);

Cast to Object
To cast to object, use the (object) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL

$a = (object) $a;
$b = (object) $b;
$c = (object) $c;
$d = (object) $d;
$e = (object) $e;
When converting into objects, most data types converts into a
object with one property, named "scalar", with the
corresponding value.

NULL values converts to an empty object.


Indexed arrays converts into objects with the index number as
property name and the value as property value.

Associative arrays converts into objects with the keys as


property names and values as property values.

Example
Converting Arrays into Objects:

$a = array("Volvo", "BMW", "Toyota"); // indexed array


$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); // associative array

$a = (object) $a;
$b = (object) $b;

Cast to NULL
To cast to NULL, use the (unset) statement:

Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL

$a = (unset) $a;
$b = (unset) $b;
$c = (unset) $c;
$d = (unset) $d;
$e = (unset) $e;
PHP Math
PHP has a set of math functions that allows you to perform
mathematical tasks on numbers.

PHP pi() Function


The pi() function returns the value of PI:

Example
Get your own PHP Server
echo(pi());

PHP min() and max() Functions


The min() and max() functions can be used to find the lowest
or highest value in a list of arguments:

Example
echo(min(0, 150, 30, 20, -8, -200));
echo(max(0, 150, 30, 20, -8, -200));

PHP abs() Function


The abs() function returns the absolute (positive) value of a
number:

Example
echo(abs(-6.7));

PHP sqrt() Function


The sqrt() function returns the square root of a number:

Example
echo(sqrt(64));

PHP round() Function


The round() function rounds a floating-point number to its
nearest integer:

Example
echo(round(0.60));
echo(round(0.49));

Random Numbers
The rand() function generates a random number:

Example
echo(rand());
To get more control over the random number, you can add the
optional min and max parameters to specify the lowest integer
and the highest integer to be returned.
For example, if you want a random integer between 10 and
100 (inclusive), use rand(10, 100):

Example
echo(rand(10, 100));

THON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT


MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R
TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO
KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA
SCIENCE

PHP Tutorial
PHP HOME
PHP Intro
PHP Install
PHP Syntax
PHP Comments
PHP Variables

PHP Echo / Print
PHP Data Types
PHP Strings
PHP Numbers
PHP Casting
PHP Math
PHP Constants
PHP Magic Constants
PHP Operators
PHP If...Else...Elseif
PHP Switch
PHP Loops
PHP Functions
PHP Arrays
PHP Superglobals
PHP RegEx

PHP Forms
PHP Form Handling
PHP Form Validation
PHP Form Required
PHP Form URL/E-mail
PHP Form Complete

PHP Advanced
PHP Date and Time
PHP Include
PHP File Handling
PHP File Open/Read
PHP File Create/Write
PHP File Upload
PHP Cookies
PHP Sessions
PHP Filters
PHP Filters Advanced
PHP Callback Functions
PHP JSON
PHP Exceptions

PHP OOP
PHP What is OOP
PHP Classes/Objects
PHP Constructor
PHP Destructor
PHP Access Modifiers
PHP Inheritance
PHP Constants
PHP Abstract Classes
PHP Interfaces
PHP Traits
PHP Static Methods
PHP Static Properties
PHP Namespaces
PHP Iterables

MySQL Database
MySQL Database
MySQL Connect
MySQL Create DB
MySQL Create Table
MySQL Insert Data
MySQL Get Last ID
MySQL Insert Multiple
MySQL Prepared
MySQL Select Data
MySQL Where
MySQL Order By
MySQL Delete Data
MySQL Update Data
MySQL Limit Data

PHP XML
PHP XML Parsers
PHP SimpleXML Parser
PHP SimpleXML - Get
PHP XML Expat
PHP XML DOM

PHP - AJAX
AJAX Intro
AJAX PHP
AJAX Database
AJAX XML
AJAX Live Search
AJAX Poll

PHP Examples
PHP Examples
PHP Compiler
PHP Quiz
PHP Exercises
PHP Server
PHP Certificate

PHP Reference
PHP Overview
PHP Array
PHP Calendar
PHP Date
PHP Directory
PHP Error
PHP Exception
PHP Filesystem
PHP Filter
PHP FTP
PHP JSON
PHP Keywords
PHP Libxml
PHP Mail
PHP Math
PHP Misc
PHP MySQLi
PHP Network
PHP Output Control
PHP RegEx
PHP SimpleXML
PHP Stream
PHP String
PHP Variable Handling
PHP XML Parser
PHP Zip
PHP Timezones

PHP Constants
Constants are like variables, except that once they are
defined they cannot be changed or undefined.

PHP Constants
A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $


sign before the constant name).

Note: Unlike variables, constants are automatically global


across the entire script.

Create a PHP Constant


To create a constant, use the define() function.

Syntax
de ne(name, value, case-insensitive);
Parameters:

• name: Specifies the name of the constant


• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name
should be case-insensitive. Default is false. Note: Defining
fi
case-insensitive constants was deprecated in PHP 7.3. PHP
8.0 accepts only false, the value true will produce a
warning.
Example
Get your own PHP Server
Create a constant with a case-sensitive name:

de ne("GREETING", "Welcome to W3Schools.com!");


echo GREETING;
Example
Create a constant with a case-insensitive name:

de ne("GREETING", "Welcome to W3Schools.com!", true);


echo greeting;

PHP const Keyword


You can also create a constant by using the const keyword.

Example
Create a constant with the const keyword:

const MYCAR = "Volvo";


echo MYCAR;
const vs. define()

• const are always case-sensitive


• define() has has a case-insensitive option.
• const cannot be created inside another block scope, like
inside a function or inside an if statement.
• define can be created inside another block scope.
fi
fi
PHP Constant Arrays
From PHP7, you can create an Array constant using the
define() function.

Example
Create an Array constant:

de ne("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];

Constants are Global


Constants are automatically global and can be used across the
entire script.

Example
This example uses a constant inside a function, even if it is
defined outside the function:

de ne("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}

myTest();
fi
fi

You might also like