Ugacomp

A Beginner’s Guide to Using Arrays in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

In PHP, arrays serve as a versatile means to store multiple values within a single variable. They play a crucial role in handling data efficiently. Let’s dive into the basics with some code examples:

Components of an Array

The components of an array include:


Variable Name

In PHP, an array is represented by a variable name, allowing you to access and manipulate multiple values under a single identifier. For example:

$numbers

This means that the variable name of an array is $numbers. You can use any variable name that fits your project you’re trying to implement

Opening and Closing Brackets

Arrays are enclosed within opening and closing brackets. There are different ways to define arrays, such as indexed arrays or associative arrays.

  • Example (Indexed Array):
$numbers = [1, 2, 3, 4, 5];
  • Example (Associative Array):
$person = ["name" => "John", "age" => 30];

Array Elements

Array elements are the values stored within the array. They can be of any data type, including numbers, strings, or even other arrays.

Example: For $numbers = [1, 2, 3, 4, 5];, the elements are 1, 2, 3, 4, and 5

Index (for Indexed Arrays)

Indexed arrays have positional indices assigned to each element, starting from 0. The index is used to access specific elements in the array.

For example, in $numbers[2], 2 is the index, and it refers to the third element (3) in the array.

Key-Value Pairs (for Associative Arrays)

Associative arrays use keys to organize elements. Each key is associated with a specific value, forming key-value pairs.

For example, in the following Associated Array:

$person = ["name" => "John", "age" => 30];

“name” and “age” are keys, and “John” and 30 are their corresponding values.

Nested Arrays (for Multidimensional Arrays)

Multidimensional arrays are arrays within arrays, creating a multi-layered structure for more complex data representation.

$matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Indexed Arrays

In PHP, the syntax for creating an indexed array involves using square brackets. There are two common methods for creating indexed arrays:

  • Method 1: Using array() Function (Older Syntax)
$colors = array("Red", "Green", "Blue");
  • Method 2: Using Square Brackets (PHP 5.4 and later)
$colors = ["Red", "Green", "Blue"];

Both methods achieve the same result, and you can choose the one that you find more readable or based on the PHP version you are using. In these examples, $colors is the variable name of the array, and the elements “Red,” “Green,” and “Blue” are placed inside the square brackets.

You can access individual elements in the array using their position index, starting from 0:

echo $colors[1]; // Outputs: Green

This code snippet prints the element at index 1 of the $colors array, which is “Green.” Indexed arrays are useful for storing ordered collections of data where each element has a numeric index associated with its position in the array.


Indexed arrays in PHP are like numbered lists where each element has a position. The positions start from 0, and you access elements using their positions.

$languages = ["HTML", "PHP", "JavaScript"];
echo $languages[1]; // Outputs: PHP

In this example, $languages is an indexed array with three elements. Each element has a position: 0, 1, and 2. So, $languages[1] gives you the element at position 1, which is “PHP”.

Think of it as having a collection of items where each item has its own number, and you can quickly grab an item by knowing its number in the list.

When do you use Indexed Arrays?

Indexed arrays in PHP can be used in various ways to store, manipulate, and retrieve data. Here are some common use cases:

  • Iterating Through an Indexed Array:

Iterating through an indexed array means going through each element of the array one by one. It’s like looking at each item in a list. In PHP, a common way to do this is by using a foreach loop. Let’s break it down for beginners:

$languages = ["HTML", "PHP", "JavaScript"];

// Using a foreach loop to go through each element in the array
foreach ($languages as $language) {
    echo $language . " "; // Output each language followed by a space
}
// Outputs: HTML PHP JavaScript

In this code, imagine you have a list called $languages with programming languages. The line “foreach ($languages as $language)” is like a command saying, “for each language in the list, do something.” The variable $language acts like a spotlight, focusing on one language at a time as we go through the list. Inside the loop, “echo $language . ” “” prints or says each language, followed by a space.

This loop keeps repeating for every language in the list, creating a combined output of “HTML PHP JavaScript” as it goes through the entire list of programming languages. It’s a simple way to go through all items in a list and perform an action on each one.

  • Adding Elements Dynamically

This means that you can expand the array by inserting new elements at runtime, without explicitly specifying the array size in advance. In PHP, indexed arrays are dynamic, and you can easily add elements to them as needed.

Here’s an example of adding elements dynamically to an indexed array:

// Initializing an empty indexed array
$fruits = [];

// Adding elements dynamically
$fruits[] = "Apple";
$fruits[] = "Banana";
$fruits[] = "Orange";

// The array now contains three elements: "Apple", "Banana", and "Orange"
print_r($fruits);

In this example, we start with an empty array called $fruits. Using the [] notation, we add elements to the array dynamically. Each time we use $fruits[], PHP automatically assigns a new index for the added element. The resulting array contains three elements: “Apple”, “Banana”, and “Orange”.

This dynamic approach is convenient because you don’t need to predefine the array size or indices. As your program runs, you can dynamically extend the array to accommodate new data.

  • Updating Elements

Updating elements in the context of indexed arrays refers to modifying the value of an existing element at a specific position within the array. In PHP, you can easily update or change the value of an element in an indexed array using its index.

Here’s an example of updating elements in an indexed array:

// Creating an indexed array
$colors = ["Red", "Green", "Blue"];

// Updating the value at index 1
$colors[1] = "Yellow";

// The array now contains: ["Red", "Yellow", "Blue"]
print_r($colors);

In this example, we start with an indexed array called $colors with three elements: “Red”, “Green”, and “Blue”. The line $colors[1] = "Yellow"; updates the value at index 1, changing “Green” to “Yellow”. The resulting array is ["Red", "Yellow", "Blue"].

Updating elements in indexed arrays is useful when you need to modify the content of the array based on certain conditions or when you receive new data that replaces existing values. It allows for dynamic adjustments to the array’s content during the execution of your program.

  • Searching for an Element

Searching for an element in the context of indexed arrays involves looking for a specific value within the array and determining its position or existence. In PHP, you can use functions like array_search() to find the index of a particular element in an indexed array.

Here’s an example of searching for an element in an indexed array:

// Creating an indexed array
$numbers = [10, 20, 30, 40, 50];

// Searching for the value 30 in the array
$key = array_search(30, $numbers);

// Outputting the index where 30 is found
echo "Index of 30: " . $key; // Outputs: Index of 30: 2

In this example, the array_search(30, $numbers) function is used to search for the value 30 within the $numbers array. If the value is found, the function returns the index (position) where it’s located. Here, the index is 2, so the output is “Index of 30: 2”.

Searching for elements in indexed arrays is beneficial when you need to locate a specific value or verify its presence in the array. It allows you to dynamically retrieve information based on the content of the array during the execution of your program.

  • Removing Elements

Removing elements in the context of indexed arrays refers to deleting or taking out specific elements from the array, thereby reducing its size. In PHP, there are various functions you can use to remove elements from an indexed array. One common method is using array_pop().

Here’s an example of removing elements from an indexed array:

// Creating an indexed array
$daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

// Removing the last element from the array
$removedDay = array_pop($daysOfWeek);

// Outputting the removed element
echo "Removed day: " . $removedDay; // Outputs: Removed day: Friday

// The array now contains: ["Monday", "Tuesday", "Wednesday", "Thursday"]
print_r($daysOfWeek);

In this example, array_pop($daysOfWeek) removes the last element from the $daysOfWeek array, which is “Friday”. The removed element is then stored in the variable $removedDay. The resulting array is ["Monday", "Tuesday", "Wednesday", "Thursday"].

Removing elements from indexed arrays is useful when you no longer need certain data or want to resize the array. It allows for dynamic adjustments to the array’s content during the execution of your program.

Associative Arrays

Associative arrays in PHP are a bit different from indexed arrays. Instead of using numeric indices, you use named keys to associate values. Think of it as creating a connection between a name and some information.

$person = [
    "name" => "John",
    "age" => 30,
    "job" => "Developer"
];
  • $person: Variable name for the array.
  • Square Brackets: Indicate the start and end of the array.
  • “name,” “age,” “job”: These are the keys. They are like labels associated with values.
  • “John”, 30, “Developer”: These are the corresponding values associated with each key.
  • Accessing Elements Using Keys: For example, $person["name"] accesses the value associated with the key “name,” which is “John.

In PHP, an associative array like $person is like a digital dossier containing information about someone. The keys, such as “name,” “age,” and “job,” act as labels, each assigned to a specific detail like “John,” 30, and “Developer.” It’s akin to having labeled compartments for different pieces of information. Accessing details is straightforward; for instance, using echo $person["name"]; means asking, “What’s the ‘name’ associated with this person?”—and it promptly responds with “John.” Associative arrays simplify data organization, making code more readable by using meaningful labels instead of numeric indices.

Associative arrays are great when you want to organize data with descriptive labels. Instead of remembering that the age is at position 1, you can simply use the key "age" to directly access the age value. It makes your code more readable and self-explanatory

How to Display Associative Arrays

Displaying associative arrays in PHP is often done using print_r() or var_dump() functions, which provide a formatted representation of the array for debugging purposes. Additionally, you can use echo to display specific elements based on their keys. Here are examples:

  • Using print_r():
$person = [
    "name" => "John",
    "age" => 30,
    "job" => "Developer"
];

print_r($person);

Output:

Array
(
    [name] => John
    [age] => 30
    [job] => Developer
)
  • Using var_dump():
$person = [
    "name" => "John",
    "age" => 30,
    "job" => "Developer"
];

var_dump($person);

Output:

array(3) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(30)
  ["job"]=>
  string(9) "Developer"
}
  • Displaying Specific Elements:
$person = [
    "name" => "John",
    "age" => 30,
    "job" => "Developer"
];

echo "Name: " . $person["name"] . "<br>";
echo "Age: " . $person["age"] . "<br>";
echo "Job: " . $person["job"];

Output:

Name: John
Age: 30
Job: Developer

These methods help you visualize the contents of associative arrays. print_r() and var_dump() are particularly useful for debugging, while using echo allows you to selectively display specific information based on the keys.

When do you use Associative Arrays?

Associative arrays in PHP are particularly useful when you need to associate specific values with descriptive labels (keys). They are beneficial in scenarios where the data can be more meaningfully represented with named identifiers. Here are some situations when you might choose to use associative arrays:

  • Storing Information about an Entity
// Example: Storing information about a student
$student = [
    "name" => "Alice",
    "age" => 22,
    "grade" => "A"
];

In this case, you use keys like “name,” “age,” and “grade” to clearly represent different attributes of a student.

  • Configurations and Settings
// Example: Storing configuration settings for a website
$siteConfig = [
    "siteName" => "My Website",
    "themeColor" => "blue",
    "enableFeature" => true
];

Associative arrays help in organizing settings for a website or application with readable and descriptive keys.

  • Database Records
// Example: Representing a user record from a database
$userRecord = [
    "username" => "john_doe",
    "email" => "[email protected]",
    "registrationDate" => "2022-01-01"
];

When fetching records from a database, associative arrays provide a convenient way to represent the data with meaningful keys.

  • Form Data Processing
// Example: Processing form data
$formData = [
    "username" => $_POST["username"],
    "email" => $_POST["email"],
    "password" => $_POST["password"]
];

When handling form submissions, associative arrays help structure the data received from the form.

  • Mapping Relationships
// Example: Mapping relationships between items
$relationshipMap = [
    "parent" => "John",
    "child" => "Alice",
    "relation" => "Father"
];

Associative arrays are beneficial when expressing relationships between entities with clear key-value associations.

Multidimensional Arrays

While multidimensional arrays may seem complex at first, they are essentially arrays whose elements are other arrays. A three-dimensional array, for instance, is an array of arrays of arrays.

If you want to use echo to display specific elements of a multidimensional array, you can do so by providing the indices for both the outer and inner arrays. Here’s an example:

$matrix = [
    ["a", "b", "c"],
    ["d", "e", "f"],
    ["g", "h", "i"]
];

// Displaying specific elements using echo
echo "Element at row 1, column 2: " . $matrix[0][1] . "<br>";
echo "Element at row 2, column 3: " . $matrix[1][2] . "<br>";

Output:

Element at row 1, column 2: b
Element at row 2, column 3: f

In this example, echo "Element at row 1, column 2: " . $matrix[0][1] . "<br>"; displays the element at the first row (index 0) and second column (index 1) of the matrix, which is “b”. Similarly, the second echo statement displays the element at the second row (index 1) and third column (index 2), which is “f”. Adjust the indices as needed to display the specific elements you want.

Using loops in multidimensional arrays

Displaying multidimensional arrays in PHP can be done using loops to iterate through the outer and inner arrays. Let’s use the example of a 2D array, also known as a matrix:

Example:

$matrix = [
    ["a", "b", "c"],
    ["d", "e", "f"],
    ["g", "h", "i"]
];

// Using nested loops to display elements
foreach ($matrix as $row) {
    foreach ($row as $element) {
        echo $element . " ";
    }
    echo "<br>";
}

Output:

a b c
d e f
g h i

Breaking it down:

  • foreach ($matrix as $row): This loop iterates through each row of the matrix.
  • foreach ($row as $element): Within each row, this loop iterates through each element.
  • echo $element . " ";: Prints each element followed by a space.
  • echo "<br>";: Adds a line break after each row to create a visually clear grid.

This approach ensures that you display each element of the multidimensional array, creating a structured output. It’s important to nest loops to traverse both the outer and inner arrays. You can adapt this method for arrays with more dimensions as needed.

When do you use multidimensional arrays?

Multidimensional arrays are used in PHP when you need to represent data in a more complex and structured manner, beyond the simplicity of a one-dimensional array. Here are common scenarios when you might choose to use multidimensional arrays:

  • Matrices and Grids

Storing and manipulating data in a grid-like structure, such as a Sudoku puzzle or game board.

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
  • Tables and Databases

Representing records in a table-like structure, simulating a database result set.

$users = [
    ["id" => 1, "name" => "Alice", "age" => 25],
    ["id" => 2, "name" => "Bob", "age" => 30],
    ["id" => 3, "name" => "Charlie", "age" => 22]
];
  • Nested Categories or Hierarchies

Organizing hierarchical data, such as categories and subcategories.

$categories = [
    "Electronics" => ["Laptops", "Smartphones", "Cameras"],
    "Clothing" => ["Men's", "Women's", "Kids"]
];

  • Images and Pixels

Representing colors in an image as RGB values in a two-dimensional array.

$dataSets = [
    ["name" => "Set A", "values" => [10, 20, 30]],
    ["name" => "Set B", "values" => [5, 15, 25]]
];
  • Storing Multiple Sets of Data

rouping related data sets together for easier management.

$dataSets = [
    ["name" => "Set A", "values" => [10, 20, 30]],
    ["name" => "Set B", "values" => [5, 15, 25]]
];

Multidimensional arrays provide a way to structure and organize data in a more meaningful way, especially when dealing with complex relationships or patterns. They allow for better representation of real-world scenarios where data naturally exists in a multi-layered structure.

Sequential Arrays

Sequential arrays are similar to indexed arrays, where elements are stored in a specific order. However, the key-value pairs are automatically assigned numeric indices.

$colors = ["red", "green", "blue"];
echo $colors[0]; // Outputs: red

Associative Sequential Arrays

Associative sequential arrays combine the features of sequential and associative arrays. They have numeric indices but also allow you to assign custom keys.

$car = [1 => "Ford", 3 => "Toyota", 5 => "Honda"];
echo $car[3]; // Outputs: Toyota

String Key Arrays

Arrays can have string keys, providing more meaningful identifiers for elements.

$grades = ["Alice" => "A", "Bob" => "B", "Charlie" => "C"];
echo $grades["Bob"]; // Outputs: B

PHP Array Functions

Now that you have a grasp of basic array concepts, let’s explore some essential array functions in PHP that will make your programming tasks more efficient.

count()

The count() function is used to get the number of elements in an array.

$numbers = [10, 20, 30, 40, 50];
echo count($numbers); // Outputs: 5

array_push() and array_pop()

These functions are used to add elements to the end and remove elements from the end of an array, respectively.

$fruits = ["apple", "orange"];
array_push($fruits, "banana");
print_r($fruits); // Outputs: Array ( [0] => apple [1] => orange [2] => banana )

$removedFruit = array_pop($fruits);
echo $removedFruit; // Outputs: banana

array_merge()

array_merge() combines two or more arrays into a single array.

$colors1 = ["red", "green"];
$colors2 = ["blue", "yellow"];
$allColors = array_merge($colors1, $colors2);
print_r($allColors);
// Outputs: Array ( [0] => red [1] => green [2] => blue [3] => yellow )

array_key_exists()

This function checks if a specified key exists in an array.

$student = ["name" => "Alice", "age" => 22];
if (array_key_exists("age", $student)) {
    echo "Age exists!";
} else {
    echo "Age does not exist!";
}
// Outputs: Age exists!

array_search()

array_search() searches for a value in an array and returns the corresponding key if found.

$grades = ["Alice" => "A", "Bob" => "B", "Charlie" => "C"];
$key = array_search("B", $grades);
echo $key; // Outputs: Bob

Sorting Arrays

Sorting arrays is a common operation in programming. PHP provides functions to sort arrays in various ways.

sort() and rsort()

The sort() function arranges array elements in ascending order, while rsort() arranges them in descending order.

$numbers = [5, 2, 8, 1, 7];
sort($numbers);
print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 7 [4] => 8 )

rsort($numbers);
print_r($numbers); // Outputs: Array ( [0] => 8 [1] => 7 [2] => 5 [3] => 2 [4] => 1 )

asort() and arsort()

asort() and arsort() are used for sorting associative arrays, and maintaining the key-value associations.

$grades = ["Alice" => "B", "Bob" => "A", "Charlie" => "C"];
asort($grades);
print_r($grades);
// Outputs: Array ( [Bob] => A [Alice] => B [Charlie] => C )

arsort($grades);
print_r($grades);
// Outputs: Array ( [Bob] => A [Charlie] => C [Alice] => B )

array_slice()

array_slice() extracts a portion of an array, allowing you to create a subset.

$fruits = ["apple", "orange", "banana", "grape", "kiwi"];
$subset = array_slice($fruits, 1, 3);
print_r($subset); // Outputs: Array ( [0] => orange [1] => banana [2] => grape )

array_unique()

array_unique() removes duplicate values from an array, providing a distinct set of elements.

$colors = ["red", "green", "blue", "green", "yellow"];
$uniqueColors = array_unique($colors);
print_r($uniqueColors); // Outputs: Array ( [0] => red [1] => green [2] => blue [4] => yellow )

Understanding these array manipulation functions will empower you to perform various operations on arrays effectively, enhancing your ability to process and analyze data in PHP. Keep exploring and practicing to master these fundamental skills.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.