Question

PHP Associative Arrays: Add Keys and Values Correctly

phparrays

Question

Given this PHP code, how can you add both the key and value from a string such as one=1 to an array so that it becomes an associative array?

$get = [];
$keyValue = 'one=1';
$rule = explode('=', $keyValue);

// array_push($get, $rule[0] => $rule[1]);

The desired result is an array like this:

[
    'one' => '1',
    'two' => '2',
]

Is there a function for adding a key and its value together, given that array_push() does not support this syntax?

Short Answer

You will learn how PHP associative arrays store values under named keys, how to add entries with bracket assignment, and when parse_str() is a better option for query-string-style input.

Concept

PHP arrays can work in two main ways:

  • Indexed arrays use numeric positions such as 0, 1, and 2.
  • Associative arrays use named keys such as 'one', 'username', or 'status'.

To add an associative entry, assign a value to a key:

$array['one'] = '1';

array_push() is intended for appending one or more values to the end of an indexed array. It does not accept a key => value expression as an argument. In PHP, => is array syntax and is only valid when defining an array, not when passing a function argument.

Associative arrays are important because they let code access meaningful data by name instead of relying on numeric positions. For example, $user['email'] is clearer and safer than $user[2].

Mental Model

Think of an associative array as a set of labelled storage drawers.

  • An indexed array is a row of drawers numbered 0, 1, 2, and so on.
  • An associative array lets you attach your own labels, such as one, email, or theme.

array_push() puts an item into the next numbered drawer. To put an item in a labelled drawer, use the label directly:

$drawers['one'] = '1';
Take Quiz

Syntax and Examples

Use square brackets to assign a value to a named key:

$settings = [];
$settings['theme'] = 'dark';
$settings['language'] = 'en';

print_r($settings);

Output:

Array
(
    [theme] => dark
    [language] => en
)

For the original key=value input, split it first and then assign the two pieces:

$get = [];
$keyValue = 'one=1';
$rule = explode('=', $keyValue, 2);

$get[$rule[0]] = $rule[1];

print_r($get);

Output:

Array
(
    [one] => 1
)

The third argument to explode() is a limit. Using 2 means PHP splits only at the first =. This is useful when the value itself may contain =.

You can also create an associative array in one expression:

$get = [
    'one' => '1',
    'two' => '2',
];

Step by Step Execution

Consider this code:

$get = [];
$keyValue = 'one=1';
$parts = explode('=', $keyValue, 2);
$get[$parts[0]] = $parts[1];

Step by step:

  1. $get = []; creates an empty array.

  2. $keyValue contains the text 'one=1'.

  3. explode('=', $keyValue, 2) separates the string at the first equals sign.

  4. $parts is now:

    ['one', '1']
    
  5. $parts[0] is 'one', which becomes the array key.

  6. $parts[1] is '1', which becomes the value.

  7. $get[$parts[0]] = $parts[1]; is equivalent to:

    $get['one'] = '1';
    
  8. The resulting array is:

    ['one' => '1']
    

Real World Use Cases

Associative arrays are used whenever data has meaningful field names.

  • HTTP request data: $_GET['page'], $_POST['email']
  • Application configuration: ['debug' => true, 'timezone' => 'UTC']
  • JSON API responses: ['success' => true, 'message' => 'Saved']
  • Database rows: ['id' => 42, 'name' => 'Ada']
  • Form validation errors: ['email' => 'Enter a valid email address']
  • Parsing URL parameters: converting page=2&sort=name into named values

For query-string-style data, PHP provides parse_str():

parse_str('one=1&two=2', $get);

print_r($get);

This produces:

[
    'one' => '1',
    'two' => '2',
]
Take Quiz

Real Codebase Usage

In real PHP projects, developers usually use direct key assignment when building data incrementally:

$response = [];
$response['success'] = true;
$response['data'] = $user;

A common validation pattern is to store errors by field name:

$errors = [];

if ($email === '') {
    $errors['email'] = 'Email is required.';
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Enter a valid email address.';
}

For parsing external input, validate the structure before reading numeric positions:

$parts = explode('=', $keyValue, 2);

if (count($parts) !== 2 || $parts[0] === '') {
    throw new InvalidArgumentException('Expected a key=value pair.');
}

$get[$parts[0]] = $parts[1];

For a complete URL query string, prefer parse_str() rather than manually splitting on both & and =:

parse_str($queryString, $params);

Be careful with untrusted input: parse it into a local array, validate allowed keys and values, and do not use it to overwrite application variables.

Common Mistakes

Using array_push() for named keys

This is invalid PHP:

array_push($get, $rule[0] => $rule[1]);

array_push() appends values only. Use key assignment instead:

$get[$rule[0]] = $rule[1];

Forgetting that explode() returns an indexed array

After this code:

$parts = explode('=', 'one=1');

The result is ['one', '1'], not ['one' => '1']. You must explicitly use the first item as the key.

Splitting every equals sign in a value

This can lose part of a value:

$parts = explode('=', 'token=abc=def');
// ['token', 'abc', 'def']

Use a limit of 2 when only the first equals sign separates key and value:

$parts = explode('=', 'token=abc=def', 2);
// ['token', 'abc=def']

Assuming the input always contains =

This causes an undefined array key warning:

$parts = explode('=', 'one');
$get[$parts[0]] = $parts[1];

Check the result first:

$parts = explode('=', 'one', 2);

if (count($parts) === 2) {
    $get[$parts[0]] = $parts[1];
}

Expecting duplicate keys to be preserved

Assigning the same key again replaces the previous value:

$get['one'] = '1';
$get['one'] = 'updated';

// ['one' => 'updated']

If one key needs multiple values, store an array as its value.

Comparisons

ApproachBest forResult
$array[] = $valueAppending to an indexed arrayAdds at the next numeric index
$array['key'] = $valueAdding or updating a named entryStores a value under a specific key
array_push($array, $value)Appending one or more indexed valuesSimilar to $array[] = $value for one value
['key' => 'value']Creating a known associative arrayDefines key-value pairs immediately
parse_str($query, $array)Parsing a full query stringConverts a=1&b=2 into an array

For one appended value, this is usually clearer:

$numbers[] = 10;

than this:

array_push($numbers, 10);

For a named value, always use direct assignment:

$numbers['first'] = 10;
Take Quiz

Cheat Sheet

// Empty array
$data = [];

// Add or replace an associative entry
$data['key'] = 'value';

// Add an indexed entry
$data[] = 'value';

// Define several named entries
$data = [
    'one' => '1',
    'two' => '2',
];

// Convert one key=value string
$parts = explode('=', 'one=1', 2);
if (count($parts) === 2) {
    $data[$parts[0]] = $parts[1];
}

// Convert a full query string
parse_str('one=1&two=2', $data);

Key rules:

  • array_push() appends values; it does not assign named keys.
  • $array['key'] = $value adds a new key or overwrites an existing key.
  • explode() returns an indexed array.
  • Query-string values are strings unless you explicitly convert them to another type.
  • Use explode('=', $text, 2) when a value may contain =.

FAQ

How do I add a key and value to an array in PHP?

Use bracket assignment:

$array['key'] = 'value';

Can array_push() add an associative key in PHP?

No. array_push() adds values to the end of an array. Use $array[$key] = $value for associative entries.

How do I convert one=1 into ['one' => '1']?

Split the string once, then assign the parts:

$parts = explode('=', 'one=1', 2);
$array[$parts[0]] = $parts[1];

How do I parse one=1&two=2 in PHP?

Use parse_str():

parse_str('one=1&two=2', $array);

Does PHP convert query-string values to integers automatically?

No. parse_str() produces string values such as '1'. Cast the value if an integer is required:

$page = (int) $params['page'];

What happens when I assign an existing array key again?

The new value replaces the old value.

Why should I use a limit of 2 with explode()?

It preserves additional = characters inside the value, such as token=abc=def.

Take Quiz

Mini Project

Description

Build a small parser for a configuration string such as theme=dark&items=20&sort=name. The project demonstrates turning key-value text into a PHP associative array and reading values by their names.

Goal

Parse a query-string-style configuration string, validate required settings, and print the resulting settings.

Requirements

Requirement 1

Take Quiz

Keep learning

Related questions

View more