Web Analytics

PHP Array Basics

Beginner~30 min read

Arrays are one of the most powerful and frequently used data structures in PHP. They allow you to store multiple values in a single variable, making it easy to work with collections of related data like user lists, product catalogs, or configuration settings.

What is an Array?

An array is an ordered collection of values. Each value is called an element, and each element has a position called an index or key.

Type Keys Example
Indexed Array Numeric (0, 1, 2...) ["Apple", "Banana", "Cherry"]
Associative Array String keys ["name" => "John", "age" => 30]
Multidimensional Arrays inside arrays [["a", "b"], ["c", "d"]]

Creating Indexed Arrays

Indexed arrays use numeric keys starting from 0:

<?php
// Modern short syntax (recommended)
$fruits = ["Apple", "Banana", "Cherry"];

// Traditional syntax
$colors = array("Red", "Green", "Blue");

// Empty array
$empty = [];

// Both syntaxes create identical arrays
var_dump($fruits);
// array(3) { [0]=> "Apple" [1]=> "Banana" [2]=> "Cherry" }
?>
Output
Click Run to execute your code
Best Practice: Always use the short array syntax [] instead of array(). It's cleaner, modern, and has been available since PHP 5.4.

Accessing Array Elements

Use square brackets with the index to access elements:

<?php
$fruits = ["Apple", "Banana", "Cherry", "Date"];

echo $fruits[0];  // Apple (first element)
echo $fruits[1];  // Banana (second element)
echo $fruits[3];  // Date (fourth element)

// Get the last element
$lastIndex = count($fruits) - 1;
echo $fruits[$lastIndex];  // Date

// Or use end() function
echo end($fruits);  // Date (moves internal pointer)
?>
Remember: Array indices start at 0, not 1! An array with 4 elements has indices 0, 1, 2, and 3.

Modifying Arrays

Arrays in PHP are mutable - you can change, add, or remove elements:

<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Modify existing element
$fruits[1] = "Blueberry";
// ["Apple", "Blueberry", "Cherry"]

// Add element at specific index
$fruits[3] = "Date";
// ["Apple", "Blueberry", "Cherry", "Date"]

// Append element (auto-assigns next index)
$fruits[] = "Elderberry";
// ["Apple", "Blueberry", "Cherry", "Date", "Elderberry"]

// Remove element
unset($fruits[2]);
// ["Apple", "Blueberry", "Date", "Elderberry"]
// Note: indices don't reindex! Index 2 is now missing
?>

Associative Arrays

Associative arrays use string keys instead of numeric indices:

Output
Click Run to execute your code

Associative Array Syntax

<?php
// Creating associative arrays
$person = [
    "name" => "John Doe",
    "age" => 30,
    "email" => "[email protected]"
];

// Accessing values
echo $person["name"];   // John Doe
echo $person["age"];    // 30

// Adding new key-value pair
$person["city"] = "New York";

// Modifying existing value
$person["age"] = 31;

// Removing a key
unset($person["email"]);
?>

Useful Array Functions

Function Purpose Example
count($arr) Get number of elements count([1,2,3]) โ†’ 3
is_array($var) Check if variable is array is_array([]) โ†’ true
empty($arr) Check if array is empty empty([]) โ†’ true
array_keys($arr) Get all keys array_keys(["a"=>1]) โ†’ ["a"]
array_values($arr) Get all values array_values(["a"=>1]) โ†’ [1]
in_array($val, $arr) Check if value exists in_array(2, [1,2,3]) โ†’ true
array_key_exists($key, $arr) Check if key exists array_key_exists("a", ["a"=>1]) โ†’ true

Quick Array Creation

<?php
// Create array of numbers
$numbers = range(1, 10);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Create array with step
$evens = range(2, 10, 2);
// [2, 4, 6, 8, 10]

// Create array of letters
$letters = range('a', 'f');
// ['a', 'b', 'c', 'd', 'e', 'f']

// Create array with repeated value
$zeros = array_fill(0, 5, 0);
// [0, 0, 0, 0, 0]

// Create array from variables
$a = 1; $b = 2; $c = 3;
$arr = compact('a', 'b', 'c');
// ["a" => 1, "b" => 2, "c" => 3]
?>

Printing Arrays

<?php
$arr = ["name" => "John", "age" => 30];

// print_r - Human-readable output
print_r($arr);
/*
Array
(
    [name] => John
    [age] => 30
)
*/

// var_dump - Detailed output with types
var_dump($arr);
/*
array(2) {
  ["name"]=> string(4) "John"
  ["age"]=> int(30)
}
*/

// JSON format
echo json_encode($arr);
// {"name":"John","age":30}
?>

Common Mistakes

1. Off-by-one index errors

<?php
$arr = ["a", "b", "c"];  // Indices: 0, 1, 2

// โŒ WRONG: Index 3 doesn't exist
echo $arr[3];  // Warning: Undefined array key 3

// โœ… CORRECT: Use valid indices
echo $arr[2];  // "c" (last element)
echo $arr[count($arr) - 1];  // "c"
?>

2. Using wrong quote style for keys

<?php
$person = ["name" => "John"];

// โŒ WRONG: Using variable syntax without quotes
echo $person[name];  // Notice: Use of undefined constant

// โœ… CORRECT: Always quote string keys
echo $person["name"];  // John
echo $person['name'];  // John (also valid)
?>

3. Assuming unset reindexes

<?php
$arr = ["a", "b", "c"];  // [0=>"a", 1=>"b", 2=>"c"]
unset($arr[1]);
// Now: [0=>"a", 2=>"c"] - Index 1 is MISSING!

print_r($arr);
// Array ( [0] => a [2] => c )

// To reindex after unset:
$arr = array_values($arr);
// Now: [0=>"a", 1=>"c"]
?>

Exercise: Contact List

Task: Create a contact list with multiple entries.

Requirements:

  • Create an array of contacts (each contact is an associative array)
  • Each contact has: name, email, phone
  • Add at least 3 contacts
  • Display all contacts in a formatted way
  • Find and display a contact by name
Show Solution
<?php
// Create contact list
$contacts = [
    [
        "name" => "Alice Smith",
        "email" => "[email protected]",
        "phone" => "555-1234"
    ],
    [
        "name" => "Bob Johnson",
        "email" => "[email protected]",
        "phone" => "555-5678"
    ],
    [
        "name" => "Carol Williams",
        "email" => "[email protected]",
        "phone" => "555-9012"
    ]
];

// Display all contacts
echo "=== Contact List ===\n\n";
foreach ($contacts as $index => $contact) {
    echo ($index + 1) . ". {$contact['name']}\n";
    echo "   Email: {$contact['email']}\n";
    echo "   Phone: {$contact['phone']}\n\n";
}

// Find contact by name
$searchName = "Bob Johnson";
$found = null;

foreach ($contacts as $contact) {
    if ($contact['name'] === $searchName) {
        $found = $contact;
        break;
    }
}

if ($found) {
    echo "Found: {$found['name']} ({$found['email']})\n";
} else {
    echo "Contact not found.\n";
}
?>

Summary

  • Arrays: Store multiple values in one variable
  • Indexed: Numeric keys starting at 0
  • Associative: String keys for named access
  • Syntax: Use [] (not array())
  • Access: $arr[0] or $arr["key"]
  • Append: $arr[] = $value
  • Remove: unset($arr[key])
  • Count: count($arr)
  • Debug: print_r() or var_dump()

What's Next?

Now that you understand basic arrays, let's explore Multidimensional Arrays - arrays within arrays that let you represent complex data structures!