PHP Arrays


In PHP, arrays are special variables that can store multiple values under a single name. They allow you to organize, access, and manipulate data efficiently. Arrays are one of the most important data structures in PHP because they are used in nearly every application, from form handling to database operations.

What Are Arrays in PHP?

An array is a collection of values, each identified by a key. These keys can be numbers (indexed arrays) or strings (associative arrays). Arrays can also be multidimensional, meaning an array can contain other arrays as elements.

Benefits of arrays:

  • Store multiple related values in one variable.

  • Simplify loops and iterations.

  • Useful for storing user input, database results, or API data.

  • Enable sorting, filtering, and mapping operations efficiently.

Types of PHP Arrays

  1. Indexed Arrays – Arrays with numeric keys starting from 0 by default.

  2. Associative Arrays – Arrays with named keys for easier identification.

  3. Multidimensional Arrays – Arrays containing other arrays as elements.

Indexed Arrays

Indexed arrays store values with numeric keys. You can create them using the array() function or the shorthand [].

<?php
// Using array() function
$fruits = array("Apple", "Banana", "Cherry");

// Using shorthand []
$colors = ["Red", "Green", "Blue"];

// Accessing elements
echo $fruits[0]; // Outputs: Apple
echo $colors[2]; // Outputs: Blue
?>

Key points:

  • Indexes start from 0 by default.

  • You can manually assign numeric keys if needed.

Associative Arrays

Associative arrays use custom keys instead of numeric indexes, making data more readable and meaningful.

<?php
// Associative array of student marks
$marks = [
    "Vicky" => 90,
    "Sanjana" => 85,
    "Amit" => 78
];

// Accessing elements
echo $marks["Sanjana"]; // Outputs: 85
?>

Advantages:

  • Use descriptive keys instead of numbers.

  • Easier to retrieve data using meaningful names.

Multidimensional Arrays

Multidimensional arrays contain arrays inside arrays, allowing complex data structures like tables or grids.

<?php
// 2D array for students and their marks
$students = [
    ["name" => "Vicky", "marks" => 90],
    ["name" => "Sanjana", "marks" => 85],
    ["name" => "Amit", "marks" => 78]
];

// Accessing elements
echo $students[1]["name"];  // Outputs: Sanjana
echo $students[2]["marks"]; // Outputs: 78
?>

Use cases:

  • Represent database query results.

  • Handle forms with multiple fields.

  • Create tables or charts dynamically.

Adding Elements to Arrays

You can add elements to an array using the square bracket [] or by assigning a key.

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

// Adding at the end
$fruits[] = "Cherry";

// Adding with a key
$fruits[5] = "Mango";

print_r($fruits);
?>

Output:

Array ( [0] => Apple [1] => Banana [2] => Cherry [5] => Mango )

Removing Elements from Arrays

Use unset() to remove elements from an array.

<?php
$colors = ["Red", "Green", "Blue"];
unset($colors[1]); // Removes "Green"
print_r($colors);
?>

Output:

Array ( [0] => Red [2] => Blue )

Tip: After using unset(), numeric keys are not automatically reindexed.

Looping Through Arrays

PHP provides multiple ways to loop through arrays.

Using for Loop (Indexed Arrays)

<?php
$fruits = ["Apple", "Banana", "Cherry"];
for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . "<br>";
}
?>

Using foreach Loop

<?php
$marks = ["Vicky" => 90, "Sanjana" => 85, "Vrinda" => 78];
foreach ($marks as $student => $score) {
    echo "$student scored $score marks.<br>";
}
?>

foreach is simpler and safer, especially for associative arrays.

Array Functions in PHP

PHP provides many built-in functions for manipulating arrays:

  • count($array) → Returns number of elements.

  • array_push($array, $value) → Adds elements at the end.

  • array_pop($array) → Removes the last element.

  • array_merge($array1, $array2) → Combines arrays.

  • in_array($value, $array) → Checks if value exists.

  • array_keys($array) → Returns all keys.

  • array_values($array) → Returns all values.

<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Cherry");
print_r($fruits);

if (in_array("Banana", $fruits)) {
    echo "Banana is in the array.";
}
?>

Sorting Arrays

You can sort arrays using functions like sort(), rsort(), asort(), and ksort():

<?php
$numbers = [3, 1, 4, 2];
sort($numbers); // Sort ascending
print_r($numbers);

$students = ["Vicky" => 90, "Sanjana" => 85];
asort($students); // Sort by value
print_r($students);
?>

Multidimensional Array Example

<?php
$products = [
    ["name" => "Laptop", "price" => 50000],
    ["name" => "Phone", "price" => 20000]
];

foreach ($products as $product) {
    echo "Product: " . $product["name"] . " - Price: " . $product["price"] . "<br>";
}
?>

Output:

Product: Laptop - Price: 50000
Product: Phone - Price: 20000

This is especially useful for displaying database results dynamically.

Best Practices

  1. Use associative arrays when keys have meaning.

  2. Use foreach for cleaner loops.

  3. Keep arrays manageable; avoid very large arrays in memory.

  4. Use array functions instead of manual loops when possible.

  5. Name arrays descriptively, e.g., $students, $products.

Summary of the Tutorial

  • Arrays store multiple values in a single variable.

  • Types: indexed, associative, multidimensional.

  • Arrays can be added, removed, sorted, and looped easily.

  • PHP has powerful built-in functions for array manipulation.

  • Arrays are essential for form handling, database operations, and dynamic content.

Arrays are the foundation for efficient data handling in PHP, and mastering them is key for any PHP developer.


Practice Questions

  1. Create an indexed array of 5 fruits and print each fruit using a for loop.

  2. Create an associative array of 3 students and their marks, then print each student’s name and mark using a foreach loop.

  3. Add a new element to an existing array of colors and print the updated array.

  4. Remove the second element from an array of numbers using unset() and print the array.

  5. Use array_push() to add two elements to an array of animals and display the array.

  6. Merge two arrays of cities into one array and print the combined array.

  7. Sort an array of numbers in ascending order using sort() and display the sorted array.

  8. Sort an associative array of products by their prices using asort() and print the result.

  9. Create a multidimensional array of 3 students with their names and marks, and print each student’s details using nested foreach loops.

  10. Check if a specific value exists in an array using in_array() and print an appropriate message.


Go Back Top