Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficiently.
- PHP offers many built-in array functions for sorting, merging, searching, and more.
- PHP Arrays can store values of different types (e.g., strings, integers, objects, or even other arrays) in the same array.
- They are dynamically sized.
- They allow you to store multiple values in a single variable, making it easier to manage related data.
Types of Arrays in PHP
There are three main types of arrays in PHP:
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you need to store a list of items where the order matters.
Now, let us understand with the help of the example:
PHP
<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>
You can also explicitly define numeric keys in an indexed array:
PHP
<?php
$fruits = array(0 => "apple", 1 => "banana", 2 => "cherry");
?>
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store data with meaningful identifiers instead of numeric indexes.
Now, let us understand with the help of the example:
PHP
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York");
echo $person["name"];
?>
3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements. These are used to represent more complex data structures, such as matrices or tables.
Now, let us understand with the help of the example:
PHP
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>
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];
Note: Both methods are valid, but the shorthand syntax is preferred for its simplicity and readability.
Accessing and Modifying Array Elements
1. Accessing Array Elements
You can access individual elements in an array using their index (for indexed arrays) or key (for associative arrays).
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple
- Accessing Associative Array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // Outputs: GFG
2. Modifying Array Elements
You can modify an existing element by assigning a new value to a specific index or key.
- Modifying Indexed Array Element:
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Mango"; // Changes "Banana" to "Mango"
echo $fruits[1]; // Outputs: Mango
- Modifying Associative Array Element:
$person = ["name" => "GFG", "age" => 25];
$person["age"] = 26; // Updates the age to 26
echo $person["age"]; // Outputs: 26
Adding and Removing Array Items
1. Adding Array Elements
You can add new elements to an array using the following methods:
- array_push(): Adds elements to the end of an indexed array.
$fruits = ["apple", "banana"];
array_push($fruits, "cherry"); // Adds "cherry" to the end
- array_unshift(): Adds elements to the beginning of an indexed array.
array_unshift($fruits, "pear"); // Adds "pear" to the beginning
- Direct assignment: Adds an element to an associative array.
$person["city"] = "New York";
2. Removing Array Elements
To remove items from an array, you can use several functions:
- array_pop(): Removes the last element from an indexed array.
array_pop($fruits);
- array_shift(): Removes the first element from an indexed array.
array_shift($fruits);
- unset(): Removes a specific element from an array by key or index.
unset($fruits[2]); // Removes the element with index 2
Array Functions
PHP provides a wide range of built-in functions to work with arrays. Here are some common array functions:
- Array Merge: The array_merge() function combines two or more arrays into one.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]
- Array Search: The in_array() function checks if a specific value exists in an array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}
- Array Sort: The sort() function sorts an indexed array in ascending order.
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers); // Outputs: [1, 1, 3, 4, 5]
To read about the PHP Array Functions read this article - PHP Array Function
Array Iteration
You can loop through arrays using loops such as foreach or for.
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
$numbers = [1, 2, 3, 4];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}
To read about the PHP Array Iteration read this article - PHP Array Iteration
Similar Reads
PHP Tutorial PHP is a widely used, open-source server-side scripting language primarily designed for web development. It is embedded directly into HTML and generates dynamic content on web pages. It allows developers to handle database interactions, session management, and form handling tasks.PHP code is execute
9 min read
Basics
PHP SyntaxPHP, a powerful server-side scripting language used in web development. Itâs simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
4 min read
PHP VariablesA variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
5 min read
PHP | FunctionsA function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP LoopsIn PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
4 min read
Array
PHP ArraysArrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP Associative ArraysAn associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
4 min read
Multidimensional arrays in PHPMulti-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Sorting Arrays in PHPSorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
4 min read
OOPs & Interfaces
MySQL Database
PHP | MySQL Database IntroductionWhat is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
4 min read
PHP Database connectionThe collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
2 min read
PHP | MySQL ( Creating Database )What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
3 min read
PHP | MySQL ( Creating Table )What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
3 min read
PHP Advance
PHP SuperglobalsPHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
6 min read
PHP | Regular ExpressionsRegular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
12 min read
PHP Form HandlingForm handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the dataâeither through the POST method (more secure, hid
4 min read
PHP File HandlingIn PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
4 min read
PHP | Uploading FileHave you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
3 min read
PHP CookiesA cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
9 min read
PHP | SessionsA session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
7 min read