spirosgyros.net

Understanding PHP Arrays: A Beginner's Guide to Data Structures

Written on

PHP, like many programming languages, employs arrays as structured data types that facilitate the organization of ordered data. These arrays can comprise various data types, with each element indexed starting from zero.

This article introduces the fundamental concepts of constructing and manipulating arrays in PHP, forming part of a seven-part series documenting my learning experience. For more insights, please refer to the links provided at the article's conclusion.

Creating Arrays

There are two primary methods to create an array in PHP:

  1. Using the built-in function: array()
  2. Employing a shorthand notation with square brackets.

For instance, these methods can be applied as follows:

$my_array = array(1, 2, 5, 9); $another_array = [0, 1, 2];

To determine the length of an array (i.e., the total number of elements), the count() function can be utilized:

echo count($my_array); // Returns 4

Accessing Elements

To retrieve a specific element from an array, index notation is used. Since indexing starts at 0, accessing the second element of an array named $my_array would be done as follows:

$my_array = [1, 2, 3, 4]; echo $my_array[1]; // Returns 2

Changing Arrays

Once an array is defined, it can be modified in several ways. New elements can be appended by using square brackets:

$my_array = [0, 1, 2]; $my_array[] = 3; // Array is now [0, 1, 2, 3]

To update an existing element, specify the index of the item you wish to alter:

$my_array = [1, 2, 3, 4]; $my_array[2] = "new value"; // $my_array is now [1, 2, "new value", 4]

Array Methods

Array methods are functions that facilitate the editing or manipulation of arrays, making operations simpler. Here are some commonly used methods:

array_push() — Adds one or more elements to the end of an array:

$my_array = [1, 2, 3]; array_push($my_array, 4, 5); // $my_array is now [1, 2, 3, 4, 5]

array_pop() — Removes the last element from an array:

$my_array = [1, 2, 3, 4]; array_pop($my_array); // $my_array is now [1, 2, 3]

array_unshift() — Adds one or more elements to the beginning of an array:

$my_array = [1, 2, 3]; array_unshift($my_array, 0); // $my_array is now [0, 1, 2, 3]

array_shift() — Removes the first element from an array:

$my_array = [1, 2, 3]; array_shift($my_array); // $my_array is now [2, 3]

Nested Arrays

As previously mentioned, arrays can contain mixed data types, including other arrays. An example of a nested array is:

$my_array = [[1, 2], [3, 4], [5, 6]];

To access elements in a nested array, use index notation for both the outer and inner arrays:

echo $my_array[1][0]; // Returns 3

Associative Arrays

An associative array, or map, is a data structure where each item is linked to a key instead of an index. They can be likened to dictionaries, linking keys to values.

For instance, if you want to store the ages of your friends, using an associative array would be more intuitive than a standard array:

$friends_ages = ["Bob" => 23, "Clive" => 49, "Amelia" => 15];

To access a value in an associative array, use the key:

echo $friends_ages["Bob"]; // Returns 23

To add an element to an associative array, you assign a value to a new key:

$friends_ages["Sara"] = 26; // Adds a key of Sara with her age

To remove an element, PHP provides the unset() function, specifying the key you wish to delete:

// Array before: ["Bob" => 23, "Clive" => 49, "Amelia" => 15] unset($friends_ages["Clive"]); // Array now: ["Bob" => 23, "Amelia" => 15]

Finally, to update an existing item's value, refer to it and assign a new value:

// After his birthday, Bob is now 24 $friends_ages["Bob"] = 24; // The array is updated with Bob's new age

For those striving to understand PHP, I hope this guide serves as a helpful starting point. I encourage you to follow along with the subsequent articles in this series.

Links to my other PHP articles (updated as published): 1. Should You Still Learn PHP in 2022? 2. PHP 101: Fundamentals 3. PHP 101: Functions 4. PHP 101: Arrays 5. PHP 101: Conditionals 6. PHP 101: Loops (coming soon) 7. PHP 101: Form Handling (coming soon) 8. PHP 101: Classes and Objects (coming soon) 9. PHP 101: My First Project (coming soon)

> If you enjoyed this article and want to read more, check out my profile for similar content. Consider becoming a Medium member for unlimited access to great ideas and writers.

> If you join Medium through this link, I will receive a small commission at no extra cost to you. Thank you!

> Thank you for reading!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Mastering Science Writing: Lessons from Ed Yong's Expertise

Explore essential science writing tips from Ed Yong, a master in the field, to enhance your skills and communicate effectively.

The Key to a Fulfilling Life: Embrace Generosity

Discover how embracing generosity can lead to a more meaningful and fulfilling life, both for yourself and those around you.

Achieve Success: 6 Essential Habits to Cultivate

Discover the six crucial habits that can pave your way to success and enhance your personal growth.

Your Aspirations Can Materialize When You're Awake

Explore how dreams can become reality and the importance of perseverance.

Exciting Updates in Apple iOS 17.1: AirPods and More!

iOS 17.1 introduces AirDrop improvements and updates to AirPods, alongside changes to Apple Music and service pricing.

Embracing Mindfulness: One Day at a Time in Meditation Journey

A reflective journey on the challenges of maintaining a consistent meditation practice and finding balance one day at a time.

Unlocking the Potential of Daily 1% Improvements for Growth

Discover how small daily improvements can lead to significant growth over time.

Finding Genuine Joy: The Path to Authentic Happiness

Discover the deeper understanding of happiness and how to break free from unhealthy attachments.