The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system’s time.
PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP.
The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number.
Getting the Time Stamp with time()
PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
time():int
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
It will produce the following output −
1699421347
We can convert a time stamp into a form that humans are comfortable with.
Converting a Time Stamp with getdate()
The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
The following table lists the elements contained in the array returned by getdate().
Sr.No
Key & Description
Example
1
secondsSeconds past the minutes (0-59)
20
2
minutesMinutes past the hour (0 – 59)
29
3
hoursHours of the day (0 – 23)
22
4
mdayDay of the month (1 – 31)
11
5
wdayDay of the week (0 – 6)
4
6
monMonth of the year (1 – 12)
7
7
yearYear (4 digits)
1997
8
ydayDay of year ( 0 – 365 )
19
9
weekdayDay of the week
Thursday
10
monthMonth of the year
January
11
0Timestamp
948370048
Now you have complete control over date and time. You can format this date and time in whatever format you want.
The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(string$format,?int$timestamp=null):string
The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
The following table lists the codes that a format string can contain −
Sr.No
Format & Description
Example
1
a‘am’ or ‘pm’ lowercase
pm
2
A‘AM’ or ‘PM’ uppercase
PM
3
dDay of month, a number with leading zeroes
20
4
DDay of week (three letters)
Thu
5
FMonth name
January
6
hHour (12-hour format – leading zeroes)
12
7
HHour (24-hour format – leading zeroes)
22
8
gHour (12-hour format – no leading zeroes)
12
9
GHour (24-hour format – no leading zeroes)
22
10
iMinutes ( 0 – 59 )
23
11
jDay of the month (no leading zeroes
20
12
l (Lower ‘L’)Day of the week
Thursday
13
LLeap year (‘1’ for yes, ‘0’ for no)
1
14
mMonth of year (number – leading zeroes)
1
15
MMonth of year (three letters)
Jan
16
rThe RFC 2822 formatted date
Thu, 21 Dec 2000 16:01:07 +0200
17
nMonth of year (number – no leading zeroes)
2
18
sSeconds of hour
20
19
UTime stamp
948372444
20
yYear (two digits)
06
21
YYear (four digits)
2006
22
zDay of year (0 – 365)
206
23
ZOffset in seconds from GMT
+5
Example
Take a look at this following example −
<?php
print date("m/d/y G.i:s \n", time()) . PHP_EOL;
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
It will produce the following output −
11/08/23 11.23:08
Today is 8 2023f November 2023, at 11.23 am
Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.
The include statement in PHP is similar to the import statement in Java or Python, and #include directive in C/C++. However, there is a slight difference in the way the include statement works in PHP.
The Java/Python import or #include in C/C++ only loads one or more language constructs such as the functions or classes defined in one file into the current file. In contrast, the include statement in PHP brings in everything in another file into the existing PHP script. It may be a PHP code, a text file, HTML markup, etc.
The “include” Statement in PHP
Here is a typical example of how the include statement works in PHP −
myfile.php
<?php
# some PHP code
?>
test.php
<?php
include 'myfile.php';
# PHP script in test.php
?>
The include keyword in PHP is very handy, especially when you need to use the same PHP code (function or class) or HTML markup across multiple PHP scripts in a project. A case in point is the creation of a menu that should appear across all pages of a web application.
Suppose you want to create a common menu for your website. Then, create a file “menu.php” with the following content.
Now create as many pages as you like and include this file to create the header. For example, now your “test.php” file can have the following content −
<html><body><?php include("menu.php"); ?><p>This is an example to show how to include PHP file!</p></body></html>
Both the files are assumed to be present in the document root folder of the XAMPP server. Visit http://localhost/test.php URL. It will produce the following output −
When PHP parser encounters the include keyword, it tries to find the specified file in the same directory from which the current script is being executed. If not found, the directories in the “include_path” setting of “php.ini” are searched.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Example
In the following example, we have a “myname.php” script with two variables declared in it. It is included in another script test.php. The variables are loaded in the global scope.
myname.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
include "myname.php";
echo "<h2>$fname $lname</h2>";
?>
When the browser visits http://localhost/test.php, it shows −
Ravi Teja
However, if the file is included inside a function, the variables are a part of the local scope of the function only.
myname.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
function showname() {
include "myname.php";
}
echo "<h2>$fname $lname</h2>";
?>
Now when the browser visits http://localhost/test.php, it shows undefined variable warnings −
Warning: Undefined variable $fname in C:\xampp\htdocs\test.php on line 7
Warning: Undefined variable $lname in C:\xampp\htdocs\test.php on line 7
include_once statement
Just like include, PHP also has the “include_once” keyword. The only difference is that if the code from a file has already been included, it will not be included again, and “include_once” returns true. As the name suggests, the file will be included just once.
“include_once” may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so it can help avoid problems such as function redefinitions, variable value reassignments, etc.
PHP – Include vs Require
The require keyword in PHP is quite similar to the include keyword. The difference between the two is that, upon failure require will produce a fatal E_COMPILE_ERROR level error.
In other words, require will halt the script, whereas include only emits a warning (E_WARNING) which allows the script to continue.
require_once keyword
The “require_once” keyword is similar to require with a subtle difference. If you are using “require_once”, then PHP will check if the file has already been included, and if so, then the same file it will not be included again.
Data types in PHP can be of “scalar type” or “compound type”. Integer, float, Boolean and string types are scalar types, whereas array and object types are classified as compound types. Values of more than one types can be stored together in a single variable of a compound type.
In PHP, objects and arrays are the two compound data types.
An array is an ordered collection of elements of other data types, not necessarily of the same type.
An object is an instance of either a built-in or a user defined class, consisting of properties and methods.
Arrays in PHP
An array is a data structure that stores one or more data values in a single variable. An array in PHP is an ordered map that associates the values to their keys.
There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to put the array elements inside square brackets.
An array which is a collection of only values is called an indexed array. Each value is identified by a positional index staring from 0.
If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type.
The array() Function in PHP
The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.
array(mixed...$values):array
Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol.
Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.
To access any element from a given array, you can use the array[key] syntax. For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.
Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.
We can unpack each element of the indexed array in the key and value variables with the foreach syntax −
PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. An object of stdClass is null to begin with. We can add properties to it dynamically.
A variable of any scalar type can also be converted to an object by type casting. The value of the scalar variable becomes the value of the object’s scalar property.
PHP provides two alternatives for declaring single or double quoted strings in the form of heredoc and newdoc syntax.
The single quoted string doesn’t interpret the escape characters and doesn’t expand the variables.
On the other hand, if you declare a double quoted string that contains a double quote character itself, you need to escape it by the “\” symbol. The heredoc syntax provides a convenient method.
Heredoc Strings in PHP
The heredoc strings in PHP are much like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables.
Heredoc Syntax
$str=<<<IDENTIFIER
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;
First, start with the “<<<” operator. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The string can span multiple lines and includes single quotes (‘) or double quotes (“).
The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string.
Example
The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. The closing identifier should not contain any other characters except a semicolon (;). Furthermore, the character before and after the closing identifier must be a newline character only.
Take a look at the following example −
<?php
$str1 = <<<STRING
Hello World
PHP Tutorial
by TutorialsPoint
STRING;
echo $str1;
?>
It will produce the following output −
Hello World
PHP Tutorial
by TutorialsPoint
Example
The closing identifier may or may not contain indentation after the first column in the editor. Indentation, if any, will be stripped off. However, the closing identifier must not be indented further than any lines of the body. Otherwise, a ParseError will be raised. Take a look at the following example and its output −
<?php
$str1 = <<<STRING
Hello World
PHP Tutorial
by TutorialsPoint
STRING;
echo $str1;
?>
It will produce the following output −
PHP Parse error: Invalid body indentation level
(expecting an indentation level of at least 16) in hello.php on line 3
Example
The quotes in a heredoc do not need to be escaped, but the PHP escape sequences can still be used. Heredoc syntax also expands the variables.
<?php
$lang="PHP";
echo <<<EOS
Heredoc strings in $lang expand vriables.
The escape sequences are also interpreted.
Here, the hexdecimal ASCII characters produce \x50\x48\x50
EOS;
?>
It will produce the following output −
Heredoc strings in PHP expand vriables.
The escape sequences are also interpreted.
Here, the hexdecimal ASCII characters produce PHP
Nowdoc Strings in PHP
A nowdoc string in PHP is similar to a heredoc string except that it doesn’t expand the variables, neither does it interpret the escape sequences.
<?php
$lang="PHP";
$str = <<<'IDENTIFIER'
This is an example of Nowdoc string.
it can span multiple lines
and include single quote ' and double quotes "
IT doesn't expand the value of $lang variable
IDENTIFIER;
echo $str;
?>
It will produce the following output −
This is an example of Nowdoc string.
it can span multiple lines
and include single quote ' and double quotes "
IT doesn't expand the value of $lang variable
The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the “<<<” operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the heredoc identifier.
Heredoc strings are like double-quoted strings without escaping. Nowdoc strings are like single-quoted strings without escaping.
To enable mathematical operations, PHP has mathematical (arithmetic) operators and a number of mathematical functions. In this chapter, the following mathematical functions are explained with examples.
PHP abs() Function
The abs() function is an in-built function in PHP iterpreter. This function accepts any number as argument and returns a positive value, disregarding its sign. Absolute value of any number is always positive.
abs(mixed$num)
PHP abs() function returns the absolute value of num. If the data type of num is float, its return type will also be float. For integer parameter, the return type is integer.
negative float number: -9.99
absolute value : 9.99
positive float number: 25.55
absolute value : 25.55
negative integer number: -45
absolute value : 45
positive integer number: 25
absolute value : 25
PHP ceil() Function
The ceil() function is an in-built function in PHP iterpreter. This function accepts any float number as argument and rounds it up to the next highest integer. This function always returns a float number as the range of float is bigger than that of integer.
ceil(float$num):float
PHP ceil() function returns the smallest integer value that is bigger than or equal to given parameter.
Example 1
The following code rounds 5.78 to its next highest integer which is 6
The exp() function calculates exponent of e that is Euler Number. PHP has a predefined constant M_E that represents Euler Number and is equal to 2.7182818284590452354. Hence, exp(x) returns 2.7182818284590452354x
This function always returns a float.
exp(float$arg):float
PHP exp() function returns the Euler Number e raised to given arg. Note that e is the base of natural algorithm. The exp() function is the inverse of natural logarithm.
Example 1
One of the predefined constants in PHP is M_LN2 which stands for loge2 and is equal to 0.69314718055994530942. So, the exp() of this value will return 2.
The floor() function is another in-built function in PHP interpreter. This function accepts any float number as argument and rounds it down to the next lowest integer. This function always returns a float number as the range of float is bigger than that of integer.
floor(float$num):float
PHP floor() function returns the largest integer less than or equal to the given parameter.
Example 1
The following example shows how to round 15.05 to its next highest integer which is 15
The intdiv() function returns the integer quotient of two integer parameters. If x/y results in “i” as division and “r” as remainder, then −
x = y*i+r
In this case, intdiv(x,y) returns “i”
intdiv(int$x,int$y):int
The “x” parameter forms numerator part of the division expression, while the “y” parameter forms the denominator part of the division expression.
PHP intdiv() function returns the integer quotient of division of “x” by “y”. The return value is positive if both the parameters are positive or both the parameters are negative.
Example 1
The following example shows that if the numerator is less than the denominator, then intdiv() function returns 0.
The log10 () function calculates the base-10 logarithm of a number. Base-10 logarithm is also called common or standard algorithm. The log10(x) function calculates log10x. It is related to natural algorithm by the following equation −
log10x=logex/loge10 ; So that
log10100=loge100/loge10 =2
In PHP, log10 is represented by log10() function
log10(float$arg):float
PHP log10() function returns the base-10 logarithm of arg.
Example 1
The following code calculates the base-10 logarithm of 100
The max () function returns the highest element in an array, or the highest amongst two or more comma separated parameters.
max(array$values):mixed
Or,
max(mixed$value1[,mixed $...]):mixed
If only one parameter is given, it should be an array of values which may be of same or different types.
If two or more parameters are given, they should be any comparable values of same or different types.
PHP max() function returns the highest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned.
Example 1
The following code returns the highest value from a numeric array.
The min () function returns the lowest element in an array, or the lowest amongst two or more comma separated parameters.
min(array$values):mixed
Or,
min(mixed$value1[,mixed $...]):mixed
If only one parameter is given, it should be an array of values which may be of same or different types
If two or more parameters are given, they should be any comparable values of same or different types
PHP min() function returns the lowest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned
Example 1
The following code returns the smallest value from numeric array.
The pow () function is used to compute the power of a certain number. It returns xy calculation, also termed as x raised to y. PHP also provides “**” as exponentiation operator.
So, pow(x,y) returns xy which is same as x**y.
pow(number$base,number$exp):number
The first parameter is the base to be raised. The second parameter is the power to which base needs to be raised.
PHP pow() function returns the base raised to the power of exp. If both arguments are non-negative integers, the result is returned as integer, otherwise it is returned as a float.
Example 1
The following example calculates 102 using pow() function −
The round() function proves useful in rounding any floating point number upto a desired precision level. Positive precision parameter causes the number to be rounded after the decimal point; whereas with negative precision, rounding occurs before the decimal point. Precision is “0” by default.
For example, round(10.6) returns 11, round(10.2) returns 10. The function always returns a floating point number.
This function also has another optional parameter called mode that takes one of the redefined constants described later.
round(float$value,int$precision,int$mode):float
Parameters
Value − A float number to be rounded.
Precision − Number of decimal digits to round to. Default is 0. Positive precision rounds given number after decimal point. Negative precision rounds the given number before decimal point.
Mode − One of the following predefined constants.
Sr.No
Constant & Description
1
PHP_ROUND_HALF_UPRounds number away from 0 when it is half way there. Hence, 1.5 becomes 2 and -1.5 to -2
2
PHP_ROUND_HALF_DOWNRounds number towards 0 when it is half way there. Hence 1.5 becomes 1 and -1.5 to -1
3
PHP_ROUND_HALF_EVENRounds the number to nearest even value
4
PHP_ROUND_HALF_ODDRounds the number to nearest odd value
PHP round() function returns a float number that by rounding the value to a desired precision.
Example 1
The following code rounds the given number to positive precision values −
The sqrt() function returns the square root of a positive float number. Since square root for a negative number is not defined, it returns NAN. This is one of the most commonly used functions. This function always returns a floating point number.
sqrt(float$arg):float
PHP sqrt() function returns the square root of the given arg number. For negative numbers, the function returns NAN.
Example 1
The following code calculates the square root of 100 −
This chapter will explain following functions related to files −
Opening a File
Reading a File
Writing a File
Closing a File
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Sr.No
Mode & Purpose
1
rOpens the file for reading only.Places the file pointer at the beginning of the file.
2
r+Opens the file for reading and writing.Places the file pointer at the beginning of the file.
3
wOpens the file for writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
4
w+Opens the file for reading and writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
5
aOpens the file for writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
6
a+Opens the file for reading and writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
Reading a File
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
Open a file using fopen() function.
Get the file’s length using filesize() function.
Read the file’s content using fread() function.
Close the file with fclose() function.
Example
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html><head><title>Reading a file using PHP</title></head><body><?php
A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
Example
The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
Integer is one of the built-in scalar types in PHP. A whole number, without a decimal point in the literal, is of the type “int” in PHP. An integer can be represented in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.
To use octal notation, a number is preceded with “0o” or “0O” (PHP 8.1.0 and earlier). From PHP 8.1.0 onwards, a number prefixed with “0” and without a decimal point is an octal number.
To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”.
Example
Take a look at this following example −
<?php
$a = 1234;
echo "1234 is an Integer in decimal notation: $a\n";
$b = 0123;
echo "0o123 is an integer in Octal notation: $b\n";
$c = 0x1A;
echo "0xaA is an integer in Hexadecimal notation: $c\n";
$d = 0b1111;
echo "0b1111 is an integer in binary notation: $d";
?>
It will produce the following output −
1234 is an Integer in decimal notation: 1234
0o123 is an integer in Octal notation: 83
0xaA is an integer in Hexadecimal notation: 26
0b1111 is an integer in binary notation: 15
PHP 7.4.0 onwards, integer literals may contain underscores (_) as separators between digits, for better readability of literals. These underscores are removed by PHP’s scanner.
Example
Take a look at this following example −
<?php
$a = 1_234_567;
echo "1_234_567 is an Integer with _ as separator: $a";
?>
It will produce the following output −
1_234_567 is an Integer with _ as separator: 1234567
PHP does not support unsigned ints. The size of an int is platform dependent. On 32 bit systems, the maximum value is about two billion. 64-bit platforms usually have a maximum value of about 9E18.
int size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX, and minimum value using the constant PHP_INT_MIN.
If an integer number happens to be beyond the bounds of the int type, or any operation results in a number beyond the bounds of the int type, it will be interpreted as a float instead.
PHP doesn’t have any operator for integer division. Hence, a division operation between an integer and a float always results in float. To obtain integral division, you may use the intval() built-in function.
In PHP, “bool” is one of the built-in scalar data types. It is used to express the truth value, and it can be either True or False. A Boolean literal uses the PHP constants True or False. These constants are case-insensitive, in the sense, true, TRUE or True are synonymous.
You can declare a variable of bool type as follows −
Boolean values are used in the construction of control statements such as if, while, for and foreach. The behaviour of these statements depends on the true/false value returned by the Boolean operators.
The following conditional statement uses the Bool value returned by the expression in the parenthesis in front of the if keyword −
$mark=60;if($mark>50)echo"pass";elseecho"fail";
Converting a Value to Boolean
Use the (bool) casting operator to convert a value to bool. When a value is used in a logical context it will be automatically interpreted as a value of type bool.
A non-zero number is considered as true, only 0 (+0.0 or -0.0) is false. Non-empty string represents true, empty string “” is equivalent to false. Similarly, an empty array returns false.
A string is a sequence of characters, like ‘PHP supports string operations.’ A string in PHP as an array of bytes and an integer indicating the length of the buffer. In PHP, a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.
PHP supports single quoted as well as double quoted string formation. Both the representations ‘this is a simple string’ as well as “this is a simple string” are valid. PHP also has Heredoc and Newdoc representations of string data type.
Single-Quoted String
A sequence of characters enclosed in single quotes (the character ‘) is a string.
$str='this is a simple string';
Example
If you want to include a literal single quote, escape it with a backslash (\).
<?php
$str = 'This is a \'simple\' string';
echo $str;
?>
It will give you the following output −
This is a 'simple' string
Example
To specify a literal backslash, double it (\\).
<?php
$str = 'The command C:\\*.* will delete all files.';
echo $str;
?>
Here is its output −
The command C:\*.* will delete all files.
Example
The escape sequences such as “\r” or “\n” will be treated literally and their special meaning will not be interpreted. The variables too will not be expanded if they appear in a single quoted string.
<?php
$str = 'This will not expand: \n a newline';
echo $str . PHP_EOL;
$x=100;
$str = 'Value of x = $x';
echo $str;
?>
It will produce the following output −
This will not expand: \n a newline
Value of x = $x
Double-Quoted String
A sequence of characters enclosed in double-quotes (” “) is another string representation.
$str="this is a simple string";
Single-quoted and double-quoted strings are equivalent except for their treatment of escape sequences. PHP will interpret certain escape sequences for special characters. For example, “\r” and “\n”.
Sequence
Meaning
\n
linefeed (LF or 0x0A (10) in ASCII)
\r
carriage return (CR or 0x0D (13) in ASCII)
\t
horizontal tab (HT or 0x09 (9) in ASCII)
\v
vertical tab (VT or 0x0B (11) in ASCII)
\e
escape (ESC or 0x1B (27) in ASCII)
\f
form feed (FF or 0x0C (12) in ASCII)
\\
backslash
\$
dollar sign
\”
double-quote
How to Escape Octal and Hexademical Characters in PHP?
PHP supports escaping an Octal and a hexadecimal number to its ASCII character. For example, the ASCII character for P is 80 in decimal. 80 in decimal to Octal is 120. Similarly, 80 in decimal to hexadecimal is 50.
To escape an octal character, prefix it with “\”; and to escape a hexadecimal character, prefix it with “\x”.
As in single quoted strings, escaping any other character will result in the backslash being printed too. The most important feature of double-quoted strings is the fact that variable names will be expanded.
Example
A double-quoted string in PHP expands the variable names (PHP variables are prefixed with $ symbol). To actually represent a “$” symbol in a PHP string, escape it by prefixing with the “\” character.
<?php
$price = 200;
echo "Price = \$ $price";
?>
You will get the following output −
Price = $ 200
String Concatenation Operator
To concatenate two string variables together, PHP uses the dot (.) operator −
In the above example, we used the concatenation operator twice. This is because we had to insert a third string. Between the two string variables, we added a string with a single character, an empty space, to separate the two variables.
The standard library of PHP includes many functions for string processing. They can be found at PHP’s official documentation (https://www.php.net/manual/en/ref.strings.php).
The strlen() Function
The strlen() function is used to find the length of a string.
Example
Let’s find the length of our string “Hello world!” −
<?php
echo strlen("Hello world!");
?>
It will produce the following output −
12
The length of a string is often used in loops or other functions, when it is important to know when the string ends (that is, in a loop, we would want to stop the loop after the last character in the string).
The strpos() Function
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match.
If no match is found, it will return FALSE.
Example
Let’s see if we can find the string “world” in our string −
<?php
echo strpos("Hello world!","world");
?>
It will produce the following output −
6
As you can see, the position of the string “world” in our string is “6”. The reason that it is “6”, and not “7”, is that the first position in the string is “0”, and not “1”.
PHP is known as a dynamically typed language. The type of a variable in PHP changes dynamically. This feature is called “type juggling” in PHP.
In C, C++ and Java, you need to declare the variable and its type before using it in the subsequent code. The variable can take a value that matches with the declared type only.
Explicit type declaration of a variable is neither needed nor supported in PHP. Hence the type of PHP variable is decided by the value assigned to it, and not the other way around. Further, when a variable is assigned a value of different type, its type too changes.
Example 1
Look at the following variable assignment in PHP.
<?php
$var = "Hello";
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
$var = 10;
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
$var = true;
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
$var = [1,2,3,4];
echo "The variable \$var is of " . gettype($var) . " type" .PHP_EOL;
?>
It will produce the following output −
The variable $var is of string type
The variable $var is of integer type
The variable $var is of boolean type
The variable $var is of array type
You can see the type of “$var” changes dynamically as per the value assigned to it. This feature of PHP is called “type juggling”.
Example 2
Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression.
If a string starts with digits, trailing non-numeric characters if any, are ignored while performing the calculation. However, PHP parser issues a notice as shown below −
int(200)
PHP Warning: A non-numeric value encountered in /home/cg/root/53040/main.php on line 4
Type Casting vs Type Juggling
Note that “type casting” in PHP is a little different from “type juggling”.
In type juggling, PHP automatically converts types from one to another when necessary. For example, if an integer value is assigned to a variable, it becomes an integer.
On the other hand, type casting takes place when the user explicitly defines the data type in which they want to cast.
Example
Type casting forces a variable to be used as a certain type. The following script shows an example of different type cast operators −