Unit II
An array is a data structure that stores one or more similar types of values in a single value. For
example, if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 lengths.
There are three different kinds of arrays and each array value is accessed using an ID which is
called array index.
There are three main types of arrays in PHP
Indexed array − An array with a numeric index. Values are stored and accessed in a
linear way.
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices.
PHP Indexed Array
PHP index is represented by a number that starts from 0. We can store number, string,s and
objects in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define an indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example 1:
<?
$season = array("Summer", "winter", "spring", "autumn");
echo "Seasons are: " . $season[0] . ", " . $season[1] . ", ". $season[2] . " and " . $season[3] .
".";
?>
Output:
Season are: summer, winter, spring and autumn
Example 2:
<?
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example:
<?
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."";
echo "John salary: ".$salary["John"]."";
echo "Kartik salary: ".$salary["Kartik"]."";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
Example:
<?
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."";
echo "John salary: ".$salary["John"]."";
echo "Kartik salary: ".$salary["Kartik"]."";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example:
<?
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
}
?>
Output:
sonoo 400000
john 500000
rahul 300000
Creating Array in PHP
In PHP, arrays can be created using two main methods:
1. Using the array() function
The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
2. Using short array syntax ([])
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
You can also create associative arrays by specifying custom keys:
$person = ["name" => "GFG", "age" => 30];
Accessing Array Elements
You can access individual elements in an array using their index (for indexed arrays) or key
(for associative arrays).
Accessing Indexed Array:
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple
Accessing Associative Array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // Outputs: GFG
Strings
In PHP, strings are one of the most commonly used data types. A string is a sequence of
characters used to represent text, such as words and sentences. Strings are enclosed in either
single quotes (' ') or double quotes (" ").
You can create a string using single quotes (' ') or double quotes (" ").
PHP supports special syntax like heredoc and nowdoc for multiline strings.
You can join (concatenate) two or more strings using the dot (.) operator.
Declaring Strings in PHP
There are four different ways to define a string literal in PHP:
single quoted
double quoted
heredoc syntax
nowdoc syntax
1. Single Quotes
Single quotes are used to define simple strings in PHP. The text within single quotes is treated
literally, meaning special characters and variables are not interpreted.
<?php
$site = 'Welcome to GeeksforGeeks';
echo $site;
?>
Output
Welcome to GeeksforGeeks
The above program compiles correctly. We have created a string, 'Welcome to
GeeksforGeeks' and stored it in a variable and printed it using an statement.
Let us now look at the program below:
<?php
$site = 'GeeksforGeeks';
echo 'Welcome to $site';
?>
Output
Welcome to $site
In the above program, the echo statement prints the variable name rather than the contents
of the variables.
This is because single-quoted strings in PHP do not process special characters.
Hence, the string is unable to identify the '$' sign as the start of a variable name.
2. Double Quotes
Unlike single-quote strings, double-quote strings in PHP are capable of processing special
characters.
<?php
echo "Welcome to GeeksforGeeks \n";
$site = "GeeksforGeeks";
echo "Welcome to $site";
?>
Output
Welcome to GeeksforGeeks
Welcome to GeeksforGeeks
Some important and frequently used special characters that are used with double-
quoted strings are explained below:
The character begins with a backslash(“\”) and is treated as escape sequences and is replaced
with special characters. Here are a few important escape sequences.
Escape Sequence Replaced By
\n New line
\t Tab space
\$ Dollar sign ($)
\r Carriage return
\\ Backslash (\)
Escape Sequence Replaced By
\" Double quote (")
\' Single quote (')
Single Quotes vs Double Quotes
Single Quotes (') Double Quotes (")
Reads the variable inside the text and shows
Shows the text exactly as you write it.
its value.
Special characters like \n don’t work. Special characters like \n (new line) do work.
Use \' if you want to add a single quote
Use \" if you want to add a double quote inside.
inside.
3. Heredoc Syntax
The syntax of Heredoc (<<<) is another way to delimit PHP strings. An identifier is given
after the heredoc (<<< ) operator, after which any text can be written as a new line is
started. To close the syntax, the same identifier is given without any tab or space.
<?php
$input = <<<testHeredoc
Welcome to GeeksforGeeks.
Started content writing in GeeksforGeeks!.
I am enjoying this.
testHeredoc;
echo $input;
?>
Output
Welcome to GeeksforGeeks.
Started content writing in GeeksforGeeks!.
I am enjoying this.
Note: Heredoc syntax is similar to the double-quoted string, without the quotes.
4. Nowdoc Syntax
Nowdoc is very much similar to the heredoc other than the parsing done in heredoc. The
syntax is similar to the heredoc syntax with symbol <<< followed by an identifier enclosed
in single quotes. The rule for nowdoc is the same as heredoc.
<?php
$input = <<<'testNowdoc'
Welcome to GeeksforGeeks.
Started content writing in GeeksforGeeks!.
testNowdoc;
echo $input;
// Directly printing string
// without any variable
echo <<<'Nowdoc'
Welcome to GFG .
Learning PHP is fun in GFG.
Nowdoc;
?>
Output
Welcome to GeeksforGeeks.
Started content writing in GeeksforGeeks!.
Welcome to GFG .
Learning PHP is fun in GFG.
Note: Nowdoc syntax is similar to the single-quoted string.
Commonly Used PHP String Functions
Function Description
strlen() Returns length of a string
strrev() Reverses a string
strtoupper() Converts string to uppercase
strtolower() Converts string to lowercase
strpos() Finds position of a substring
Function Description
str_replace() Replaces text within a string
substr() Extracts part of a string
trim() Trim spaces from both ends
explode() Splits string into an array
implode() Joins array elements into a string
The strlen() Function
The strlen() function returns the string's length, which is the number of characters before the
first null termination character. This is less than the amount of RAM allocated to the string,
which can be measured with the sizeof operator.
Syntax
Here is the syntax for the strlen() function −
strlen($str);
It takes single parameter which is the string we need to check the length for.
Example
Let's find the length of our string "Hello world!" –
<?php
echo strlen("Hello world!");
?>
It will produce the following output −
12
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.
Syntax
Here is the syntax for the strpos() function −
strpos ($str, $find , $start)
This function accepts two parameters. The first parameter is the string to search, and the second
parameter is the substring to search for.
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
Date-Time
PHP provides functions to work with dates and times, allowing developers to display the
current date/time, manipulate and format dates, and perform operations like date
comparisons, time zone adjustments, and more.
In this article, we'll discuss PHP date and time.
Why are Date and Time Important in PHP?
In web development, date and time are important for:
Displaying the current date and time on a website (e.g., last updated time, current date
for a blog post).
Compare and manipulate dates (e.g., calculating age from a birthdate).
Store date and time information in databases.
Handle time zone adjustments for users in different regions.
Getting the Current Date and Time
The simplest way to get the current date and time in PHP is by using the date() function. This
function formats the current local date and time based on the format string you provide.
Syntax:
date(format, timestamp);
In this syntax:
The format parameter in the date() function specifies the format of the returned date and
time.
The timestamp is an optional parameter, if it is not included, then the current date and
time will be used.
Example 1: Display Current Date
<?php
echo date("Y-m-d"); // Output: 2025-04-04
?>
Output
2025-04-04
In this example:
Y stands for the four-digit year.
m represents the two-digit month.
d represents the two-digit day.
Example 2: Display Current Date and Time
<?php
echo date("Y-m-d H:i:s");
?>
Output
2025-04-04 12:34:11
In this example:
H represents hours in 24-hour format.
i represents minutes.
s represents seconds.
Date Formatting in date() function
The format parameter of the date() function is a string that can contain multiple characters,
allowing to generate the dates in various formats. Date-related formatting characters that are
commonly used in the format string:
d: Represents the day of the month, two digits with leading zeros (01 or 31).
D: Represents the day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents the year in two digits (08 or 14).
Y: Represents the year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>
Output
Today's date in various formats:
04/04/2025
04-04-2025
04.04.2025
04.Apr.2025/Fri
PHP time() Function
The time() function is used to get the current time as a Unix timestamp (the number of
seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
The following characters can be used to format the time string:
h: Represents the hour in 12-hour format with leading zeros (01 to 12).
H: Represents the hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the time() function in PHP.
<?php
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
Output
1743772332
April 04, 2025 01:12:12 PM
Get Your Time Zone
In PHP, you can easily get the current time zone using the date_default_timezone_get()
function. This function returns the default time zone set in your PHP configuration or the
time zone that has been explicitly set within your script using date_default_timezone_set().
Syntax:
date_default_timezone_get();
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Output
The time is 01:26:09pm
Create a Date With mktime()
PHP mktime() Function is used to create the timestamp for a specific date and time. If no
date and time are provided, the timestamp for the current date and time is returned.
Syntax:
mktime(hour, minute, second, month, day, year)
Example: The below example explains the usage of the mktime() function in PHP.
<?php
$d=mktime(18, 21, 50, 4, 5, 2025);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Output
Created date is 2025-04-05 06:21:50pm
Create a Date From a String With strtotime()
In PHP, the strtotime() function is another way to convert a textual date/time description into
a Unix timestamp. This allows you to easily create dates from human-readable strings and
perform calculations or formatting with them.
Syntax:
strtotime(time, now)
Example: The below example explains the usage of the strtotime() function in PHP.
<?php
$d=strtotime("6:30pm April 4 2025");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Output
Created date is 2025-04-04 06:30:00pm