How to push both value and key into PHP array
The snippet you are looking at demonstrates a common stumbling block for developers transitioning from procedural thinking to object-oriented patterns or modern PHP standards. You want to build an associative array where keys are derived from a specific format, like one=1, splitting the string to extract the label and the value. The core confusion stems from how array_push operates versus how native array assignment works.
array_push is designed strictly for appending elements to the end of an array. It accepts one or more values as arguments. When you call it like this, PHP treats every argument passed to it as a value. If you pass an associative pair, it doesn't know how to bind that value to a specific key; it simply appends the whole thing as a new element at index 0, then index 1, and so on. This results in a numerically indexed array containing arrays, not the flat associative structure you need for lookups like $GET['one'].
To achieve the output $GET[one => 1, two => 2], you need to bypass array_push entirely and use direct assignment or methods that specifically handle key-value pairs. The most idiomatic approach in modern PHP (version 5.4+) is using the spread operator (...) with an array of arrays, or simply iterating through a loop.
Here is how you can refactor your logic to parse the keys correctly and populate the array:
$GET = [];
$key = 'one=1';
// Split the key into parts
$parts = explode('=', $key);
if (count($parts) === 2) {
// Direct assignment is the most readable way to add a single pair
$GET[$parts[0]] = $parts[1];
}
If you need to process multiple strings like this in a loop, direct assignment inside the loop remains the most efficient method:
$GET = [];
$inputs = ['one=1', 'two=2', 'three=3'];
foreach ($inputs as $key) {
$parts = explode('=', $key);
// Validate that we actually got a key and a value before assigning
if (count($parts) === 2) {
$GET[$parts[0]] = $parts[1];
}
}
print_r($GET);
// Output: Array ( [one] => 1 [two] => 2 [three] => 3 )
Why array_push fails here
Understanding the mechanics of array_push clarifies why it cannot be used for this specific task. The function signature is effectively array_push(array &$array, mixed ...$values). It expects a list of values to append. Even if you wrap your key-value pair in another array, array_push will treat that wrapper as a single value to be appended.
// This will create a numerically indexed array containing one element
// which is the string "one=1" or an array depending on how you pass it,
// but it will NOT create $GET['one'] => '1'
array_push($GET, [$parts[0] => $parts[1]]);
If you attempt to push an associative array directly, PHP converts that sub-array into a string representation or simply appends it as a single entity, breaking the flat associative structure required for quick key lookup.
Handling Edge Cases and Pitfalls
When parsing strings like one=1, you must consider data integrity. The explode function splits based on the first occurrence of the delimiter by default. If your input contains multiple equals signs, such as key=value=extra, a simple explode will produce three parts: ['key', 'value', 'extra']. Your current logic might inadvertently treat value as the key and extra as the value if you aren't careful with array indexing.
Always verify that count($parts) is exactly 2 before attempting assignment. If it is not, the string is malformed for your expected format, and assigning it could lead to unexpected behavior or overwriting existing keys. Furthermore, be wary of empty keys. If a string starts with =, explode will return an empty string as the key. While PHP allows empty string keys, they often indicate a parsing error in web contexts (like form submissions).
For larger applications handling complex query strings or form data, manual string manipulation is rarely the best path. Frameworks like Laravel provide robust utilities for this exact scenario. If you are working within the Laravel ecosystem, consider using parse_str which handles URL encoding and duplicate keys automatically:
parse_str('one=1&two=2', $GET);
This function is specifically designed to populate an associative array from a string of query parameters, handling the key-value separation logic internally while respecting PHP's rules for duplicate keys.