PHP / PHP Arrays and Strings

Working with Arrays in PHP

This tutorial provides an in-depth look at arrays in PHP, including their declaration, access, and manipulation. It is a fundamental concept for anyone looking to master PHP.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores array manipulation and string handling in PHP.

Working with Arrays in PHP

1. Introduction

In this tutorial, we will be taking an in-depth look at arrays in PHP. An array is a data structure that stores one or more values in a single value. For those who are looking to master PHP, understanding arrays is fundamental as they are used in almost every major PHP application.

By the end of this tutorial, you will learn how to declare, access, and manipulate arrays in PHP. The only prerequisite is a basic understanding of PHP syntax.

2. Step-by-Step Guide

Defining Arrays

In PHP, the array() function is used to create an array. It takes any number of comma-separated key => value pairs as arguments.

$array = array(
  "foo" => "bar",
  "bar" => "foo",
);

Accessing Array Elements

Array elements are accessed using their key. Here's an example:

// Define the array
$array = array(
  "foo" => "bar",
  "bar" => "foo",
);

// Access the elements
echo $array["foo"]; // Outputs: bar
echo $array["bar"]; // Outputs: foo

Manipulating Arrays

PHP provides several functions to manipulate arrays. For instance, array_push() is used to add one or more elements to the end of an array.

$array = array("apple", "banana");
array_push($array, "orange", "pear");

print_r($array);
// Outputs: Array ( [0] => apple [1] => banana [2] => orange [3] => pear )

3. Code Examples

Example 1: Numeric Array

// Numeric array
$fruits = array('Apple', 'Banana', 'Mango');

// Accessing elements by their numeric index
echo $fruits[0]; // Apple
echo $fruits[1]; // Banana
echo $fruits[2]; // Mango

Example 2: Associative Array

// Associative array
$ages = array("John" => 22, "Mary" => 23, "James" => 21);

// Accessing elements by their key
echo $ages['John']; // 22
echo $ages['Mary']; // 23
echo $ages['James']; // 21

Example 3: Multidimensional Array

// Multidimensional array
$persons = array(
    "John" => array(
        "Age" => 22,
        "Gender" => "Male"
    ),
    "Mary" => array(
        "Age" => 23,
        "Gender" => "Female"
    )
);

// Accessing elements
echo $persons['John']['Age']; // 22
echo $persons['Mary']['Gender']; // Female

4. Summary

In this tutorial, we've covered how to declare, access, and manipulate arrays in PHP. We've also discussed different types of arrays - numeric, associative, and multidimensional arrays.

As a next step, you can learn about PHP array functions like array_pop(), array_shift(), array_unshift(), array_push(), etc. You can also learn about sorting arrays in PHP.

5. Practice Exercises

Exercise 1: Create a numeric array with five elements and print the third element.

Solution:

$array = array(1, 2, 3, 4, 5);
echo $array[2]; // Outputs: 3

Exercise 2: Create an associative array with three elements and print the value of each element.

Solution:

$array = array("apple" => "fruit", "carrot" => "vegetable", "chicken" => "meat");

echo $array["apple"]; // Outputs: fruit
echo $array["carrot"]; // Outputs: vegetable
echo $array["chicken"]; // Outputs: meat

Exercise 3: Add two new elements to the beginning of the associative array created in Exercise 2.

Solution:

$array = array("apple" => "fruit", "carrot" => "vegetable", "chicken" => "meat");

$array = array("milk" => "drink", "bread" => "grain") + $array;

print_r($array);
// Outputs: Array ( [milk] => drink [bread] => grain [apple] => fruit [carrot] => vegetable [chicken] => meat )

Remember to always practice what you learn to get a better understanding of the concept. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help