Programming

PHP Array Add Element: Guide to Adding to Empty Arrays

Learn how to add elements to empty arrays in PHP using bracket notation and array_push(). Compare performance and see practical examples for dynamic array manipulation.

1 answer 1 view

How do I add elements to an empty array in PHP? If I define an array without specifying its size like $cart = array();, can I simply add elements using $cart[] = 13;, $cart[] = 'foo';, and $cart[] = $obj;? Do PHP arrays have an add method like cart.add(13)?

In PHP, you can absolutely add elements to an empty array using bracket notation like $cart[] = 13; or the array_push() function. PHP arrays are dynamic structures that don’t require pre-defining size, and while there’s no cart.add(13) method like in some other languages, you have multiple efficient options for adding elements to your arrays.

Contents


Adding Elements to Empty Arrays

When you define an empty array in PHP with $cart = array(); or the modern syntax $cart = [];, you can indeed add elements using bracket notation. This approach is straightforward and intuitive:

php
// Define an empty array
$cart = array();

// Add elements using bracket notation
$cart[] = 13; // Adds integer 13
$cart[] = 'foo'; // Adds string 'foo'
$cart[] = $obj; // Adds object $obj

// The array now contains all three elements
print_r($cart);

PHP arrays are dynamic data structures that automatically resize as you add elements. Unlike some programming languages, PHP doesn’t require you to pre-allocate memory or specify array sizes. The bracket notation $cart[] = $value; automatically appends the value to the end of the array and increments the internal pointer.

For adding multiple elements at once, the array_push() function provides a convenient alternative:

php
// Define an empty array
$products = [];

// Add multiple elements at once
array_push($products, 'Laptop', 'Mouse', 'Keyboard');

// The array now contains all three products
print_r($products);

Bracket Notation vs array_push()

Both methods achieve the same result—adding elements to the end of an array—but they have different characteristics that make them suitable for different scenarios.

Bracket Notation ($array[] = $value;)

Bracket notation is the most common and concise way to add elements to PHP arrays:

php
$colors = [];
$colors[] = 'Red';
$colors[] = 'Green';
$colors[] = 'Blue';

This approach is syntactically clean and directly expresses the intent of adding an element to an array. It’s particularly useful when you’re adding elements one at a time in sequence.

array_push() Function

The array_push() function serves as a wrapper around bracket notation but offers a different syntax, especially useful when adding multiple elements:

php
$numbers = array();
array_push($numbers, 1, 2, 3, 4, 5);

According to the official PHP documentation, array_push() is essentially a convenience function that does the same thing as repeated bracket notation. The function takes the array as the first parameter, followed by any number of values to add to the array.

Key Differences

  1. Syntax: Bracket notation uses $array[] = $value; while array_push() uses array_push($array, $value1, $value2, ...);
  2. Readability: For single elements, bracket notation is often more readable. For multiple elements, array_push() can be cleaner.
  3. Return Value: array_push() returns the new count of elements in the array, while bracket notation returns the added value.

Performance Considerations

When working with PHP arrays, performance differences between bracket notation and array_push() become important, especially in performance-critical applications.

Benchmark Results

Performance tests consistently show that bracket notation is faster than array_push() for adding single elements:

php
// Test with bracket notation
$test1 = [];
$start = microtime(true);
for($i = 0; $i < 100000; $i++) {
 $test1[] = $i;
}
$end = microtime(true);
echo "Bracket notation: " . ($end - $start) . " seconds\n";

// Test with array_push()
$test2 = [];
$start = microtime(true);
for($i = 0; $i < 100000; $i++) {
 array_push($test2, $i);
}
$end = microtime(true);
echo "array_push(): " . ($end - $start) . " seconds\n";

The benchmark results from community testing show that bracket notation can be more than twice as fast as array_push() for single-element additions. This performance difference occurs because:

  1. Function Call Overhead: array_push() is a function call, which involves additional processing compared to direct bracket notation
  2. Parameter Handling: array_push() needs to handle mixed parameters and perform type checking, which adds overhead

When to Use Each Method

Use bracket notation when:

  • Adding single elements to an array
  • Performance is critical
  • You prefer concise syntax

Use array_push() when:

  • Adding multiple elements in one call
  • You need the return value (new array count)
  • You’re working with code that already uses this pattern

Interestingly, when adding multiple elements at once, the performance difference becomes less significant or may even reverse in some cases, as array_push() can be more efficient than multiple separate bracket operations.


Practical Examples

Let’s explore practical scenarios for adding elements to empty arrays in PHP applications.

Basic Shopping Cart Implementation

A common use case for adding elements to arrays is implementing a shopping cart:

php
// Initialize empty cart
$cart = [];

// Add items to cart
$cart[] = [
 'id' => 1,
 'name' => 'Laptop',
 'price' => 999.99,
 'quantity' => 1
];

$cart[] = [
 'id' => 2,
 'name' => 'Mouse',
 'price' => 29.99,
 'quantity' => 2
];

// Calculate total
$total = 0;
foreach($cart as $item) {
 $total += $item['price'] * $item['quantity'];
}

echo "Total: $" . number_format($total, 2);

Dynamic Form Processing

When processing form data, you often need to collect multiple values into an array:

php
// Process checkbox values
$interests = [];
if(isset($_POST['interests'])) {
 foreach($_POST['interests'] as $interest) {
 $interests[] = htmlspecialchars($interest);
 }
}

// Process multiple file uploads
$uploadedFiles = [];
if(isset($_FILES['files']['name'])) {
 foreach($_FILES['files']['name'] as $key => $name) {
 if($_FILES['files']['error'][$key] == 0) {
 $uploadedFiles[] = [
 'name' => $name,
 'tmp_name' => $_FILES['files']['tmp_name'][$key],
 'size' => $_FILES['files']['size'][$key]
 ];
 }
 }
}

Database Results Processing

When fetching database results, you often build arrays of records:

php
// Using PDO
$users = [];
$stmt = $pdo->query("SELECT id, name, email FROM users");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
 $users[] = $row;
}

// Using MySQLi
$products = [];
$result = $mysqli->query("SELECT * FROM products");
while($product = $result->fetch_assoc()) {
 $products[] = $product;
}

These examples demonstrate how adding elements to empty arrays is a fundamental operation in PHP development, used across various application types from simple scripts to complex web applications.


Common Use Cases

Understanding when and how to add elements to arrays helps in writing more efficient PHP code. Here are common scenarios where adding elements to empty arrays is particularly useful.

Configuration Arrays

Many PHP applications use configuration arrays that are built dynamically:

php
// Build configuration from various sources
$config = [];

// Add default values
$config[] = ['debug' => false, 'cache' => true];

// Add environment-specific settings
if(file_exists('config.local.php')) {
 $config[] = include 'config.local.php';
}

// Merge all configurations (last one takes precedence)
$finalConfig = array_merge(...$config);

Data Collection and Aggregation

When collecting data from multiple sources, arrays are essential:

php
// Collect sensor readings
$sensorData = [];
$sensorData[] = ['temperature' => 22.5, 'humidity' => 45, 'timestamp' => time()];
$sensorData[] = ['temperature' => 23.1, 'humidity' => 43, 'timestamp' => time() + 60];

// Collect user feedback
$feedback = [];
$feedback[] = ['user_id' => 123, 'rating' => 5, 'comment' => 'Great product!'];
$feedback[] = ['user_id' => 456, 'rating' => 4, 'comment' => 'Good but could be better'];

Event Handling

In event-driven systems, you often collect event handlers:

php
// Event system
$events = [];

// Add event handlers
$events[] = ['event' => 'user.register', 'handler' => 'sendWelcomeEmail'];
$events[] = ['event' => 'user.login', 'handler' => 'logActivity'];
$events[] = ['event' => 'user.logout', 'handler' => 'clearSession'];

// Process events
foreach($events as $event) {
 if($event['event'] == $currentEvent) {
 call_user_func($event['handler']);
 }
}

API Response Building

When constructing API responses, arrays are commonly used:

php
// Build API response
$response = [];

// Add metadata
$response[] = ['status' => 'success', 'code' => 200];

// Add data
$response[] = ['users' => $users, 'total' => count($users)];

// Convert to JSON
header('Content-Type: application/json');
echo json_encode($response);

These use cases demonstrate the versatility of adding elements to arrays in PHP, showing how this fundamental operation supports various programming patterns and architectural approaches.


Sources

  1. PHP: array_push - Manual — Official documentation for array_push function and array element addition: https://www.php.net/manual/en/function.array-push.php
  2. How To Add Elements To An Empty Array In PHP? — Comprehensive tutorial on PHP array methods and element addition: https://www.uptimia.com/questions/how-to-add-elements-to-an-empty-array-in-php
  3. PHP add to array - Everything you need to know — Detailed guide on PHP array operations and syntax: https://flexiple.com/php/php-add-to-array
  4. How to Add Elements to an Empty Array in PHP — Tutorial Republic’s guide to PHP array manipulation: https://www.tutorialrepublic.com/faq/how-to-add-elements-to-an-empty-array-in-php.php
  5. Langage de programmation - PHP - Référence de procédures et fonctions - ARRAY_PUSH — Performance comparison of array_push vs bracket notation: https://www.gladir.com/CODER/PHP/array_push.htm
  6. Speed Test: array_push vs $array[] — Community benchmark showing performance differences: https://snipplr.com/view/759/speed-test-arraypush-vs-array

Conclusion

Adding elements to empty arrays in PHP is a fundamental operation that every PHP developer should master. The two primary methods—bracket notation ($array[] = $value;) and the array_push() function—each have their place depending on your specific needs. While PHP doesn’t have an add() method like some other languages, these built-in approaches provide all the functionality you need for dynamic array manipulation.

For most use cases, bracket notation offers better performance and cleaner syntax, especially when adding single elements. However, array_push() can be more convenient when adding multiple elements at once or when you need the return value (the new array count). Understanding these differences allows you to write more efficient and readable PHP code in your applications.

Authors
Verified by moderation
Moderation
PHP Array Add Element: Guide to Adding to Empty Arrays