Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Create and Use Arrays in PHP

Posted on October 18, 2026






How to Create and Use Arrays in PHP – Complete Guide for Beginners


How to Create and Use Arrays in PHP

Arrays are one of the most powerful data structures in PHP, allowing you to store multiple values in a single variable. Whether you’re building a simple list or a complex data model, mastering arrays is essential for every PHP developer.

Table of Contents

  • What Is an Array in PHP?
  • Creating Indexed Arrays
  • Creating Associative Arrays
  • Creating Multidimensional Arrays
  • Common Array Functions
  • Looping Through Arrays
  • Best Practices & Tips

What Is an Array in PHP?

An array in PHP is a special variable that can hold more than one value at a time. PHP arrays are ordered maps, meaning they can use both integer and string keys. This flexibility makes them suitable for:

  • Storing lists of items (indexed arrays)
  • Mapping names to values (associative arrays)
  • Representing tables, matrices, or JSON‑like structures (multidimensional arrays)

Creating Indexed Arrays

Indexed arrays use numeric keys that start at 0 by default. There are three common ways to create them:

1. Using the array() construct

$colors = array('red', 'green', 'blue');
echo $colors[1]; // outputs: green

2. Using short array syntax (PHP 5.4+)

$fruits = ['apple', 'banana', 'cherry'];
echo $fruits[2]; // outputs: cherry

3. Adding elements dynamically

$numbers = [];
$numbers[] = 10;   // key 0
$numbers[] = 20;   // key 1
$numbers[5] = 30;  // explicit key 5

Creating Associative Arrays

Associative arrays let you use meaningful string keys instead of numeric indexes.

Basic syntax

$person = [
    'first_name' => 'John',
    'last_name'  => 'Doe',
    'age'        => 28
];
echo $person['first_name']; // outputs: John

Mixing numeric and string keys

$mixed = [
    0          => 'zero',
    'one'      => 1,
    2          => 'two',
    'three'    => 3
];

Creating Multidimensional Arrays

Multidimensional arrays are arrays that contain other arrays. They are perfect for representing tables, matrices, or JSON objects.

Example: A simple matrix

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

Example: A list of users

$users = [
    [
        'id'    => 1,
        'name'  => 'Alice',
        'email' => 'alice@example.com'
    ],
    [
        'id'    => 2,
        'name'  => 'Bob',
        'email' => 'bob@example.com'
    ]
];
echo $users[0]['email']; // outputs: alice@example.com

Common Array Functions in PHP

PHP ships with a rich set of built‑in functions that make working with arrays fast and expressive.

Counting Elements

$count = count($fruits); // returns 3

Adding & Removing Items

// Push to the end
array_push($fruits, 'date');

// Pop from the end
$last = array_pop($fruits);

// Unshift (add to beginning)
array_unshift($fruits, 'elderberry');

// Shift (remove from beginning)
$first = array_shift($fruits);

Merging Arrays

$all = array_merge($colors, $fruits);

Searching

$index = array_search('banana', $fruits); // returns the numeric key
$exists = in_array('green', $colors);      // true or false

Sorting

sort($numbers);          // ascending, reindexes keys
rsort($numbers);         // descending
asort($person);          // sort by value, preserve keys
ksort($person);          // sort by key

Looping Through Arrays

Iterating over arrays is a daily task. The most common loop is foreach, but for and while can also be useful.

Using foreach

// Indexed array
foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit\n";
}

// Associative array
foreach ($person as $key => $value) {
    echo "$key => $value\n";
}

Using for with numeric indexes

for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . PHP_EOL;
}

Iterating a multidimensional array

foreach ($users as $user) {
    echo $user['name'] . ' (' . $user['email'] . ')' . PHP_EOL;
}

Best Practices & Tips

  • Use short array syntax ([]) for cleaner code.
  • Prefer foreach for readability and automatic key handling.
  • Never mix data types within the same array unless it’s intentional; it can lead to subtle bugs.
  • Validate keys when using associative arrays to avoid undefined index notices.
  • Leverage built‑in functions instead of writing custom loops; they’re usually faster and more reliable.
  • Document complex structures with comments or type‑hinting (PHP 7.4+ supports typed properties).

Conclusion

Arrays are the backbone of data handling in PHP. By mastering indexed, associative, and multidimensional arrays, along with the powerful suite of array functions, you’ll be equipped to build robust applications, manipulate data efficiently, and write cleaner, more maintainable code.

Ready to put your new skills into practice? Start coding, experiment with the examples above, and explore PHP’s extensive array reference for deeper insights.


Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Pakistan Tour Sri Lanka 2026: A Subcontinent Showdown
  • Pakistan Tour New Zealand 2025: Exploring the Kiwi Conditions
  • Pakistan Tour South Africa 2025: A Test of Grit and Skill
  • Pakistan Tour England: A Classic Rivalry Renewed
  • How to Create and Use Arrays in PHP

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check