Understanding PHP Arrays

PHP arrays are created using the array() constructor or the short syntax []. You can define arrays with numeric keys, string keys, or even nested arrays. Here's a basic example:

<?php
// Indexed array
$fruits = ['apple', 'banana', 'orange'];

// Associative array
$user = [
    'name' => 'John',
    'age' => 30,
    'email' => 'john@example.com'
];

// Multidimensional array
$students = [
    ['name' => 'Alice', 'score' => 90],
    ['name' => 'Bob', 'score' => 85]
];

Common Array Operations

PHP provides a rich set of functions to work with arrays. Below is a summary of some of the most commonly used functions:

FunctionDescriptionExample
array()Creates a new array$arr = array('a', 'b', 'c');
count()Returns the number of elements in an arrayecho count($fruits);
array_keys()Returns all the keys from an arrayprint_r(array_keys($user));
array_values()Returns all the values from an arrayprint_r(array_values($students));
array_map()array_map() applies a function to a PHP arrayprint_r(array_map('strtoupper', $fruits));
array_filter()Filters an array for a PHP arrayprint_r(array_filter($students, function($s) { return $s['score'] > 80; }));

Iterating Through Arrays

Iterating through arrays is a common task in PHP. You can use foreach loops or built-in functions like array_map() and array_filter() to process array elements.

<?php
$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as $num) {
    echo "Number: $num\n";
}

For more complex operations, array_map() is useful:

<?php
$squared = array_map(function($n) { return $n * $n; }, $numbers);
print_r($squared);

Modifying Arrays

PHP offers several functions to modify arrays, such as array_push(), array_pop(), array_shift(), and array_unshift().

<?php
$colors = ['red', 'green'];

array_push($colors, 'blue'); // Add to the end
array_unshift($colors, 'yellow'); // Add to the beginning

print_r($colors); // Output: Array ( [0] => yellow [1] => red [2] => green [3] => blue )

Advanced Array Functions

Some advanced functions like array_merge() and array_combine() allow you to combine arrays or create key-value pairs:

<?php
$first = ['a', 'b', 'c'];
$second = [1, 2, 3];

$combined = array_merge($first, $second);
print_r($combined); // Output: Array ( [0] => a [1] => b [2] => c [3] => 1 [4] => 2 [5] => 3 )

$keys = ['name', 'age'];
$values = ['John', 30];

$assoc = array_combine($keys, $values);
print_r($assoc); // Output: Array ( [name] => John [age] => 30 )

Learn more with official resources