Question
In PHP, if I create an empty array like this:
$cart = array();
can I add elements to it like this?
$cart[] = 13;
$cart[] = "foo";
$cart[] = $obj;
If so, is that the normal way to append items to an array in PHP? Is there also an add() method, such as cart.add(13)?
Short Answer
By the end of this page, you will understand how to add elements to arrays in PHP, the difference between [] and array_push(), why PHP arrays do not use an add() method, and how this works in real code.
Concept
In PHP, arrays are dynamic, which means you usually do not declare a fixed size ahead of time. You can start with an empty array and append values whenever you need.
The most common way to add an item to the end of an array is:
$cart[] = 13;
When PHP sees empty square brackets [], it automatically places the value at the next available numeric index.
For example:
$cart = array();
$cart[] = 13;
$cart[] = "foo";
This becomes:
array(
0 => 13,
1 => "foo"
)
PHP arrays do not have an instance method like add(). In other words, this is not valid PHP:
$cart->add(13); // not how PHP arrays work
That style is common in some other languages or collection classes, but a plain PHP array is a built-in language type, not an object with methods.
Mental Model
Think of a PHP array like a shopping list written on paper.
- You start with a blank list:
array() - Each time you use
[], PHP writes the new item on the next empty line - You do not need to manually track the line number unless you want to
Example:
$cart = array();
$cart[] = "Apples";
$cart[] = "Bread";
PHP is effectively doing this for you:
- Put
"Apples"at index0 - Put
"Bread"at index1
So [] means: append this value at the end.
Syntax and Examples
The main ways to add elements to an array in PHP are:
Append to the end with []
$cart = array();
$cart[] = 13;
$cart[] = "foo";
$cart[] = $obj;
This is the most common approach.
Using short array syntax
In modern PHP, this is equivalent and more commonly written as:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
Append with array_push()
$cart = [];
array_push($cart, 13);
array_push($cart, "foo", "bar");
array_push() is useful when adding multiple items in one call.
Assign to a specific key
PHP arrays can also use custom keys:
Step by Step Execution
Consider this example:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = "bar";
print_r($cart);
Step by step:
-
$cart = [];- Creates an empty array.
- Current value:
[] -
$cart[] = 13;- PHP finds the next numeric index, which is
0. - Current value:
[0 => 13] - PHP finds the next numeric index, which is
-
$cart[] = "foo";- PHP appends at index
1. - Current value:
[0 => 13, 1 => ] - PHP appends at index
Real World Use Cases
Here are common situations where appending to arrays is used in PHP:
Building a shopping cart
$cart = [];
$cart[] = ["id" => 101, "name" => "T-shirt", "qty" => 2];
$cart[] = ["id" => 205, "name" => "Shoes", "qty" => 1];
Collecting validation errors
$errors = [];
if (empty($email)) {
$errors[] = "Email is required.";
}
if (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters.";
}
Preparing API response data
$items = [];
$items[] = ["id" => 1, "title" => "First post"];
[] = [ => , => ];
Real Codebase Usage
In real PHP projects, developers usually append to arrays in a few common patterns.
1. Collecting results in loops
$products = [];
foreach ($rows as $row) {
$products[] = [
'id' => $row['id'],
'name' => $row['name']
];
}
This is very common when transforming data.
2. Collecting validation errors
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email address';
}
if ($age < 18) {
$errors[] = 'You must be at least 18';
}
3. Building configuration arrays
$config = [];
$config['debug'] = true;
$config['timezone'] = 'UTC';
Common Mistakes
Beginners often make these mistakes when working with PHP arrays.
Mistake 1: Expecting an add() method
Broken code:
$cart = [];
$cart.add(13);
Why it is wrong:
- PHP arrays are not used with dot syntax
- PHP does not provide an array instance method called
add()
Correct code:
$cart = [];
$cart[] = 13;
Mistake 2: Forgetting the $ on variables
Broken code:
cart[] = 13;
Correct code:
$cart[] = 13;
Mistake 3: Using an undefined constant instead of a string
Broken code:
$cart[] = obj;
Comparisons
Here is how the main options compare:
| Approach | Syntax | Best for | Notes |
|---|---|---|---|
| Append with brackets | $cart[] = 13; | Adding one item | Most common and concise |
array_push() | array_push($cart, 13); | Adding multiple items at once | Works well, but more verbose for one item |
| Assign by key | $cart['id'] = 13; | Associative arrays | Used when values need named keys |
[] vs array_push()
| Feature |
|---|
Cheat Sheet
Quick reference
Create an empty array
$cart = array();
or:
$cart = [];
Append one item
$cart[] = 13;
Append multiple items
array_push($cart, 13, "foo", "bar");
Set a specific key
$cart['name'] = 'Book';
Store objects or arrays
$cart[] = $obj;
$cart[] = ['id' => 1, 'name' => 'Pen'];
Rules to remember
FAQ
Is $array[] = $value the normal way to add to an array in PHP?
Yes. It is the most common way to append a single value to the end of a PHP array.
Does PHP have an add() method for arrays?
No. Plain PHP arrays do not have an add() method. Use [] or array_push() instead.
What is the difference between [] and array_push() in PHP?
Both can append values. [] is simpler for one item, while array_push() can add multiple items in one call.
Can a PHP array contain different data types?
Yes. A PHP array can contain integers, strings, booleans, arrays, objects, and more.
Do I need to define the size of an array first in PHP?
No. PHP arrays grow automatically as you add items.
Can I add an object to a PHP array?
Yes, as long as you use a variable such as $obj.
$cart[] = $obj;
Should I use array() or ?
Mini Project
Description
Create a simple shopping cart script in PHP that starts with an empty array and appends products to it. This demonstrates the most common way to build a list dynamically as data becomes available.
Goal
Build a PHP script that stores several cart items in an array and prints the final cart contents.
Requirements
- Start with an empty array.
- Add at least three items to the cart.
- Make at least one item an associative array with product details.
- Output the final array so you can inspect its structure.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.