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.
PHP also provides the function array_push() to append one or more values:
array_push($cart, 13);
However, for adding a single item, $cart[] = 13; is usually simpler and more common.
This matters because arrays are used everywhere in PHP: storing query results, building lists of items, collecting form data, and preparing JSON responses. Knowing the standard way to append values helps you read and write normal PHP code confidently.
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:
$cart = [];
$cart["product"] = "Book";
$cart["quantity"] = 2;
This creates an associative array.
Example: mixed values
PHP arrays can contain different types:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = true;
$cart[] = ["name" => "Pen", "price" => 1.50];
This is valid, although in real applications it is often better to keep array contents consistent when possible.
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 => "foo"] - PHP appends at index
-
$cart[] = "bar";- PHP appends at index
2. - Current value:
[0 => 13, 1 => "foo", 2 => "bar"] - PHP appends at index
-
print_r($cart);- Output:
Array ( [0] => 13 [1] => foo [2] => bar )
Now compare it with array_push():
$cart = [];
array_push($cart, 13, "foo", "bar");
print_r($cart);
The final array is the same.
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"];
$items[] = ["id" => 2, "title" => "Second post"];
Grouping database results
$names = [];
while ($row = fetchRow()) {
$names[] = $row['name'];
}
Logging events during a script
$log = [];
$log[] = "Script started";
$log[] = "User loaded";
$log[] = "Email sent";
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';
This uses named keys instead of numeric append.
4. Returning structured data from functions
function buildResponse(array $users): array {
$result = [];
foreach ($users as $user) {
$result[] = [
'id' => $user['id'],
'name' => $user['name']
];
}
return $result;
}
5. Guard clauses with error arrays
$errors = [];
if (empty($title)) {
$errors[] = 'Title is required';
}
if (!empty($errors)) {
return $errors;
}
Even though arrays do not have methods like add(), they are still extremely flexible and central to day-to-day PHP development.
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;
If obj is meant to be a variable, it must be written with $.
Correct code:
$cart[] = $obj;
If it is meant to be text, quote it:
$cart[] = "obj";
Mistake 4: Confusing numeric arrays and associative arrays
$cart = [];
$cart[] = 'Book';
$cart['quantity'] = 2;
This is valid PHP, but mixing styles can make code harder to understand.
A clearer structure might be:
$item = [
'name' => 'Book',
'quantity' => 2
];
Mistake 5: Using array_push() for a single item everywhere
This works:
array_push($cart, 13);
But for one item, this is usually clearer:
$cart[] = 13;
Mistake 6: Assuming arrays have fixed size
In PHP, arrays grow as needed. You do not usually predefine their size like in some other languages.
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 | [] | array_push() |
|---|---|---|
| Adds one item | Excellent | Works, but more verbose |
| Adds multiple items | One statement per item | Can add many in one call |
| Readability | Very simple | Slightly more explicit |
| Common usage | Most common | Less common for single values |
PHP arrays vs arrays in some other languages
| Language style | Example | Notes |
|---|---|---|
| PHP append | $cart[] = 13; | Built-in syntax |
| PHP function | array_push($cart, 13); | Function, not method |
| JavaScript method | cart.push(13) | Array object method |
| Java/C# style | list.add(13) | Collection method |
This is why cart.add(13) feels familiar if you come from another language, but it is not how plain PHP arrays work.
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
- PHP arrays are dynamic
- You do not need to declare a size first
[]appends to the end of the array- There is no
add()method for plain PHP arrays - Use
$variable, notvariable - Use quotes for strings
Common choice
For one item:
$cart[] = $value;
For many items at once:
array_push($cart, $a, $b, $c);
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 []?
Both work. [] is shorter and more common in modern PHP code.
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.