Arrays in PHP
PHP arrays are versatile data structures that store multiple values in a single variable. Here's a comprehensive overview:
1. Array Types
a. Indexed Arrays
- Numeric keys (0-based index)
$fruits = ["Apple", "Banana", "Cherry"]; echo $fruits[1]; // Output: Banana
b. Associative Arrays
- Named keys (string indices)
$person = [ "name" => "John", "age" => 30, "city" => "New York" ]; echo $person["name"]; // Output: John
c. Multidimensional Arrays
- Arrays containing other arrays
$matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; echo $matrix[1][2]; // Output: 6
2. Array Creation
// Method 1: Short syntax (PHP 5.4+)
$colors = ["Red", "Green", "Blue"];
// Method 2: array() construct
$colors = array("Red", "Green", "Blue");
// Associative array
$user = array("username" => "jdoe", "id" => 101);
3. Common Functions
a. Adding Elements
$fruits = ["Apple"];
$fruits[] = "Banana"; // Add to end
array_unshift($fruits, "Mango"); // Add to beginning
b. Removing Elements
array_pop($fruits); // Remove last element
array_shift($fruits); // Remove first element
unset($fruits[1]); // Remove specific index
c. Array Operations
// Merge arrays
$combined = array_merge($array1, $array2);
// Split into chunks
$chunks = array_chunk($fruits, 2);
// Check if value exists
if (in_array("Apple", $fruits)) { ... }
// Search for key
$key = array_search("Banana", $fruits);
// Sort arrays
sort($fruits); // Sort values
ksort($person); // Sort by keys
asort($person); // Sort associative array by values
d. Array Iteration
// Indexed array
foreach ($fruits as $fruit) {
echo $fruit;
}
// Associative array
foreach ($person as $key => $value) {
echo "$key: $value";
}
4. Useful Array Functions
| Function | Description |
|---|---|
count($array) | Get number of elements |
array_keys($array) | Get all keys |
array_values($array) | Get all values |
array_flip($array) | Swap keys and values |
array_reverse($array) | Reverse element order |
implode($glue, $array) | Join elements into string |
explode($delimiter, $string) | Split string into array |
array_map(callback, $array) | Apply function to all elements |
array_filter($array) | Filter elements using callback |
5. Advanced Techniques
a. Array Destructuring (PHP 7.1+)
[$a, $b] = [10, 20];
echo $a; // 10
// Associative
["name" => $n, "age" => $a] = $person;
b. Spread Operator (PHP 7.4+)
$parts = ["Apple", "Banana"];
$fruits = [...$parts, "Cherry"];
c. Null Coalescing Assignment (PHP 7.4+)
$array['key'] ??= 'default'; // Set if not exists
6. Common Use Cases
a. Form Data Handling
// HTML: <input name="user[name]">
$userData = $_POST['user'] ?? [];
echo $userData['name'];
b. Database Results
// Fetch multiple rows
$users = $db->query("SELECT * FROM users")->fetchAll();
foreach ($users as $user) {
echo $user['email'];
}
c. Configuration Arrays
$config = [
'db' => [
'host' => 'localhost',
'user' => 'admin'
]
];
7. Best Practices
- Use Short Syntax: Prefer
[]overarray() - Type Hinting: Use
arraytype hints in functionsfunction processArray(array $data) { ... } - Immutable Operations: Use
+for merging (preserves keys)$combined = $array1 + $array2; - Avoid Mixed Types: Keep consistent data types in arrays
- Validation: Check existence with
isset()or??before access
8. Common Pitfalls
- Undefined Index: Always check existence before access
// Wrong: echo $arr['key']; // Right: echo $arr['key'] ?? 'default'; - Reference Issues:
$a = [1, 2]; $b = &$a; // Reference - changes affect both - Automatic Type Juggling:
$arr = ["10", 2]; sort($arr); // Becomes [2, "10"] (numeric sort)
9. Performance Tips
- Preallocate Large Arrays:
$large = array_fill(0, 10000, null); - Use References for Large Data:
foreach ($hugeArray as &$item) { ... } - Avoid Count in Loops:
// Bad: for($i=0; $i<count($arr); $i++) // Good: $cnt = count($arr); for($i=0; $i<$cnt; $i++)
PHP arrays are powerful tools that combine features of lists, dictionaries, and sets. Mastering them is essential for effective PHP development!
Post a Comment