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


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

FunctionDescription
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

  1. Use Short Syntax: Prefer [] over array()
  2. Type Hinting: Use array type hints in functions
    function processArray(array $data) { ... }
    
  3. Immutable Operations: Use + for merging (preserves keys)
    $combined = $array1 + $array2;
    
  4. Avoid Mixed Types: Keep consistent data types in arrays
  5. 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!

Comments

Popular posts from this blog

Introduction to Computer System

The Farmer and the Delayed Harvest: A Tale of Patience and Triumph

7 different types of logo styles