Bab 2 PHP
Bab 2 PHP
String, Numbers,
Casting, Math,
Constants
• 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.
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.
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.
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.
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.
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 . "!";
}
}
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.
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.
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.
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!":
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!":
Example
Search for the text "world" in the string "Hello world!":
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:
Example
Split the string into an array. Use the space character as
separator:
$x = "Hello World!";
$y = explode(" ", $x);
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.
Example
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
An easier and better way is by using the power of double
quotes.
Example
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
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.
Example
Start the slice at index 6 and go all the way to the end:
$x = "Hello World!";
echo substr($x, 6);
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).
Escape Character
To insert characters that are illegal in a string, use an escape
character.
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:
\$ PHP variables
\n New Line
\r Carriage Return
\t Tab
\f Form Feed
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.
• 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.
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.
• 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.
• 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);
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.
Example
Cast float and string to integer:
echo "<br>";
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.
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.
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 . "!";
}
}
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.
Example
Converting Arrays into Objects:
$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.
Example
Get your own PHP Server
echo(pi());
Example
echo(min(0, 150, 30, 20, -8, -200));
echo(max(0, 150, 30, 20, -8, -200));
Example
echo(abs(-6.7));
Example
echo(sqrt(64));
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));
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.
Syntax
de ne(name, value, case-insensitive);
Parameters:
Example
Create a constant with the const keyword:
Example
Create an Array constant:
de ne("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
Example
This example uses a constant inside a function, even if it is
defined outside the function:
function myTest() {
echo GREETING;
}
myTest();
fi
fi